问题
I'm having scenario like choosing/entering of date from datepicker. I have used jquery plugin for datepicker. It worked perfectly.
As I said earlier, user also having an advantage of entering date directly in textbox instead of choosing from calendar. At this stage, as we all know that the user may happen to enter the date wrongly. Hence I stepped in jquery datepicker validation plugin. There I found some articles to proceed.
The useful links are as follows,
keithwood
Jsfiddle
Chridam says
What I tried is:
As first link says(Keith wood), I tried with datepicker.validation.js. But nothing happens when i enter the wrong date. Below is the complete code which I tried,
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="UTF-8">
<title> Test for date picker</title>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/south-street/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>
<script type="text/javascript" src="jquery.ui.datepicker.validation.js"></script>
<script src="demo.js" type="text/javascript"></script>
</head>
<body>
<form id="validateForm" action="#">
<script >
$('#validateForm').validate({
errorPlacement: $.datepicker.errorPlacement,
rules: {
validDefaultDatepicker: {
required: true,
dpDate: true
},
validBeforeDatepicker: {
dpCompareDate: ['before', '#validAfterDatepicker']
},
validAfterDatepicker: {
dpCompareDate: { after: '#validBeforeDatepicker' }
},
validTodayDatepicker: {
dpCompareDate: 'ne today'
},
validSpecificDatepicker: {
dpCompareDate: 'notBefore 01/01/2012'
}
},
messages: {
validFormatDatepicker: 'Please enter a valid date (yyyy-mm-dd)',
validRangeDatepicker: 'Please enter a valid date range',
validMultiDatepicker: 'Please enter at most three valid dates',
validAfterDatepicker: 'Please enter a date after the previous value'
}
});
</script>
<p>
Select Date:
<input type="text" size="10" name="validDefaultDatepicker" id="validDefaultDatepicker"/></p>
<script>
$(function () {
$('#validDefaultDatepicker').datepicker();
});
</script>
</form>
As per the second link(chridam), I tried with type = date concept directly. It gave me hope as it worked perfectly. Though the solution is nice, it is not working IE browsers. Below is the complete code,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#jQueryValidateTest").validate();
$("[type=date]").datepicker({
onClose: function () {
$(this).valid();
}
});
});
</script>
<style>
.valid {
background: green;
color: #fff;
}
.error {
background: red;
color: #fff;
}
</style>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<form id="jQueryValidateTest">
<input type="date" required>
</form>
</td>
</tr>
</table>
</body>
</html>
Hope I'm not confusing you. Kindly help me to overcome this hurdle. Thanks in advance.
回答1:
If I understand your question completely you'd like to have custom input validation for dates. It's a problem I recently had for a flight booking website (live ex.)
One thing for sure is that input fields of type date
are nice, but not very x-browser because they roll out with they're own date format, depending on the device/OS/browser culture. So my solution is for text
input types. It also uses jquery UI datepicker and unobtrusive validation plugin.
To conquer this hurdle one big advantage that IS inside jQuery UI datepicker, apart from the missing manual input validation, is the option constrainInput which allows only the characters by it's current format. That's already a big win!
On a second note jQuery UI also comes with culture files to instantiate datepickers against a custom format.
Building on top of that, I believe a custom validation method is required.
Then one big difference compared to your setup might be the use of minDate
& maxDate
options. Not sure if that's applicable to you but that's how I got it to validate correctly.
/**
* @description resolves an issue with chrome & safari date validation
* @param {String} format : regional dateformat
*/
setValidator: function (format) {
var self = this, // scope
settings = this.settings, // object literal
data = settings.data, // mapping for data-attributes
options = settings.options; // my custom behavior options
$.validator.addMethod('date', function (value, element) {
var inst, // jquery ui datepicker data inst object => very handy
parts, // split the user input
minDate = new Date(), // create a min range
maxDate = new Date(minDate), // create a max range
newDate; // the date to be validated in the end
// unrequired fields
if (this.optional(element)) {
return true;
}
try {
// get the data instance from the element, put there by jquery-ui
// warning: inline datepickers have their instance on the resp. div
inst = options.isInline ? self.findDatepicker($(element)).data(data.datepicker) : $(element).data(data.datepicker);
// determine the epoch timestamps of the input, based on the options minDate and maxDate, for calculation
minDate = typeof inst.settings.minDate === 'object' ? inst.settings.minDate.getTime() : minDate.setDate(minDate.getDate() + parseInt(inst.settings.minDate.replace(/[+d]/g, ''), 10));
maxDate = maxDate.setDate(maxDate.getDate() + parseInt(inst.settings.maxDate.replace(/[+d]/g, ''), 10));
// correct months 0-based
// correct 2digit years
// add hours to the maxDate
parts = value.split('/');
if (parts.length === 3) {
parts[0] = parseInt(parts[0], 10);
parts[1] = parseInt(parts[1], 10) - 1;
parts[2] = parseInt(parts[2], 10) < 100 ? parseInt(parts[2], 10) + 2000 : parseInt(parts[2], 10);
// notice how I switch the parts against the default format
newDate = new Date(parts[2], parts[1], parts[0], 23, 59, 59, 0).getTime();
if ($(element).data(data.maxdate)) {
newDate = newDate - (new Date(newDate).getHours() * 60 * 60 * 1000);
}
// unfortunately not very usefull as it doesn't return anything when false => value.split('/')
//$.datepicker.parseDate(format, value);
} else {
newDate = 0;
}
return newDate >= minDate && newDate <= maxDate;
}
catch (err) {
console.log(err);
}
});
}
Basically I loop over every jQuery datepicker:
- get/set the culture from i18n culture files with ajax =>
'/scripts/lib/jquery-ui/ui/i18n/datepicker-{{culture}}.js'
- set the validator with the format param =>
self.setValidator(regional.dateFormat);
- set the options for datepicker =>
$('.datepicker').datepicker(options);
Hope that makes sense a bit or at least push you in the right direction. If something is unclear, ask away ... as I realize this is not a copy/paste solution ^^
来源:https://stackoverflow.com/questions/30161644/datepicker-validation-is-not-working-on-using-jquery-plugin