Wednesday 15 January 2014

How can I make this date optional in jQuery Validation? -



How can I make this date optional in jQuery Validation? -

i have datepicker on required date field. attempting create no longer required, i'm not seeing how that.

the form using jquery validation. see there required attribute can set false, error appears still. here code using:

setupvalidationfordates: function() { $('input.datepicker').each(function(i, el) { $.validator.addmethod('sdateformat', function(value, element, param) { homecoming string(value).match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}/); }, 'must have format yyyy-mm-dd'); $(el).rules('add', { required: false, sdateformat: true, validdatestring: true, }); }); }

the message seen about, "must have format yyyy-mm-dd" showing when field empty. need validate if value present, allow empty values. how can accomplish this, required: false not seem working expect.

thanks

you've written custom method if field required... why you're getting error message while field still empty.

you need add together this.optional(element) || custom method follows...

$.validator.addmethod('sdateformat', function(value, element, param) { homecoming this.optional(element) || string(value).match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}/); }, 'must have format yyyy-mm-dd');

now custom method not fire unless entered relevant field.

this edit custom method makes "optional". in other words, if later wanted field required, add together required: true rule declaration without touching custom method.

secondly, need declare addmethod once create new method. should taken out of .each() it's unnecessarily beingness called repeatedly. can remove required: false it's default behavior of required rule.

setupvalidationfordates: function() { $.validator.addmethod('sdateformat', function(value, element, param) { homecoming 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 anymore, it's default sdateformat: true, validdatestring: true }); }); }

jquery jquery-validate

No comments:

Post a Comment