I have a datepicker on a previously required date field. I am attempting to make it no longer required, but I\'m not seeing how to do that.
The form is using jQuery
Check if the value is null before you valid it with regex. return true if null. Or you could update your regex to include a space so its still considered valid if only containing empty string.
You've written your custom method as if the field is required
... that is why you're getting the error message while the field is still empty.
You would need to add this.optional(element) ||
to your custom method as follows...
$.validator.addMethod('sDateFormat', function(value, element, param) {
return this.optional(element) || String(value).match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}/);
}, 'Must have format YYYY-MM-DD');
Now the custom method will not fire unless something is entered into the relevant field.
This edit to the custom method simply makes it "optional". In other words, if you later wanted the field to be required
, simply add required: true
to the rule declaration without touching this custom method.
Secondly, you only need to declare addMethod
once to create the new method. It should be taken out of your .each()
as it's unnecessarily being called repeatedly. You can also remove required: false
as it's already the default behavior of the required
rule.
setUpValidationForDates: function() {
$.validator.addMethod('sDateFormat', function(value, element, param) {
return this.optional(element) || String(value).match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}/);
}, 'Must have format YYYY-MM-DD');
$('input.datepicker').each(function(i, el) {
$(el).rules('add', {
// required: false, // don't need this anymore, it's default
sDateFormat: true,
validDateString: true
});
});
}