I have some client-side validation that checks to ensure that the EndDate
is greater than or equal to StartDate
. The validation works, but it's not firing as I would like it to. I would like it to fire as soon as a date is selected on the datepicker for EndDate
. How can I accomplish this? I've tried the following:
Datepicker code:
$(".datepicker").datepicker({
changeMonth: true,
changeYear: true,
onClose: function () {
$(this).focusout();
}
});
Validation code:
$("#EndDate").focusout(function () {
jQuery.validator.addMethod('datetimegreaterthanorequal', function (value, element, params) {
var startDateValue = $(params.element).val();
return Date.parse(value) >= Date.parse(startDateValue);
}, '');
jQuery.validator.unobtrusive.adapters.add('datetimegreaterthanorequal', ['startdate'], function (options) {
var prefix = options.element.name.substr(0, options.element.name.lastIndexOf('.') + 1),
other = options.params.startdate,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(':input[name=' + fullOtherName + ']')[0];
options.rules['datetimegreaterthanorequal'] = {
element: element
};
if (options.message) {
options.messages['datetimegreaterthanorequal'] = options.message;
}
});
function appendModelPrefix(value, prefix) {
if (value.indexOf('*.') === 0) {
value = value.replace('*.', prefix);
}
return value;
}
})
Although the answer from Mark will work, you should note that it will validate the entire form. If you just want to validate the related input field, you would be better off doing:
$(".datepicker").datepicker({
onSelect: function () {
$(this).trigger("focus").trigger("blur");
}
});
This fakes the user clicking inside the input field and leaving it again.
You are assigning the validators inside of our .focusout()
event. Remove that block completely as you want them assigned only once.
You can easily trigger validation on the onSelect
option like the following:
$(".datepicker").datepicker({
changeMonth: true,
changeYear: true,
onSelect: function () {
$("#myForm").valid();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With