Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validation this.optional(element) always false

I'm trying to get familiar with jQuery validation custom methods and seems to get confused a bit. why this.optional(element) inside my custom method always returns 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>

in case if element is not required and it's value is not empty - validation method is called and i need to return true in this case. But this.optional(el) is always false :(

How can i solve it ? How can i check if element is required or not inside custom method? Thanks.

like image 616
Roman Kupin Avatar asked Apr 23 '10 13:04

Roman Kupin


1 Answers

optional is false if the value is not empty, so you can perform validation on the field, but only if it's not empty. For example, if the e-mail address is optional, you have to validate the format, but only if value is provided. optional returns true if value is not provided, so the rest of the evaluation is not performed. This is the purpose of this method. If you need value not to be empty, it have to be required. if you need it either empty or not, you do not need validation at all.

like image 169
Maxim Krizhanovsky Avatar answered Sep 21 '22 01:09

Maxim Krizhanovsky