开发者

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').开发者_C百科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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜