jQuery Validate plugin, one out of two fields is required

后端 未结 2 1116
萌比男神i
萌比男神i 2020-12-02 00:52

I have a form with 2 fields; mobile no. and telephone no.

at least 1 of the fields has to be filled in, but both can also be filled.

I need jquery validate t

相关标签:
2条回答
  • 2020-12-02 00:53

    Using the optional additional-methods.js file, there is a method called require_from_group that does exactly what you request. (You must use at least version 1.11.1 of the plugin in order to avoid a past bug.)

    rules: {
        mobile:{
            require_from_group: [1, '.mygroup']
        },
        telephone:{
            require_from_group: [1, '.mygroup']
        }
    },
    ....
    

    The 1 parameter is how many from the group are required. In the HTML markup, the fields in your group must contain a class matching the class specified in your second parameter.

    <input type="text" class="mygroup" name="mobile" />
    <input type="text" class="mygroup" name="telephone" />
    

    Working DEMO: http://jsfiddle.net/NfcxX/

    My demo also shows the groups option which combines the multiple error messages into one.

    0 讨论(0)
  • 2020-12-02 01:04
    <input type="text" name="mobile" id="regMobile">
    <input type="text" name="telephone" id="regTelephone">
    
    rules: {
                mobile:{
                    required: {
                        depends: function(element) {
                            return $("#regTelephone").val() == ''
                        }
                    }
                },
                telephone:{
                    required: {
                        depends: function(element) {
                            return $("#regMobile").val() == ''
                        }
                    }
                }
    }  
    
    0 讨论(0)
提交回复
热议问题