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.
jquery jquery-validate
Roman kupin
source share