JQuery validation this.optional (element) is always false

I am trying to get familiar with custom jQuery validation methods and it seems a bit confused. why does this.optional (element) inside my custom method always return false?

here is an example of my code:

<script type="text/javascript"> $(document).ready(function(){ $.validator.addMethod('customemethod', function(val, el){ return this.optional(el) || false; }, 'custom method says its INVALID !'); $('#myform').validate({ignore: '*[ignore]'}); $('#validate').click(function(){ $('#result').text($('#myform').validate().form()); return false; }); }); </script> <form id="myform"> <div><input type="text" id="customfield" name="customfield" /></div> <script type="text/javascript"> $(document).ready(function(){$('#customfield').rules('add', { required: true, customemethod: true } ) } ); </script> <div><input type="text" id="customfield2" name="customfield2" /></div> <script type="text/javascript"> $(document).ready(function(){$('#customfield2').rules('add', { required: false, customemethod: true } ) } ); </script> <div id="result"></div> <input id="validate" type="submit" /> </form> 

if the element is not required, but the value is not empty, the verification method is called and I need to return true in this case. But this.optional (el) is always false: (

How can i solve this? How can I check if an element is required or not inside the user method? Thanks.

+6
jquery jquery-validate
source share
1 answer

optional is false if the value is not empty, so you can perform a check in the field, but only if it is not empty. For example, if an email address is optional, you should check its format, but only if a value is provided. optional returns true if no value is specified, so the rest of the evaluation is not performed. This is the purpose of this method. If you want the value not to be empty, it must be required. if you need it, either empty or not, you don't need a check.

+7
source share