Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate plugin, one out of two fields is required

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 to throw an error if none of them are filled only.

I have achieved this with:

rules: {
            mobile:{
                required: {
                    depends: function(element) {
                        return $("#regTelephone").val() === '';
                    }
                }
            },
            telephone:{
                required: {
                    depends: function(element) {
                        return $("#regMobile").val() === '';
                    }
                }
            }
}  

however, if only one field is empty, this field still gets the 'valid' class, which I don't want as my valid css has a green border (so the empty field still gets a green border)

so: how do I get the field which is empty (providing the other has a value) to not get the valid class and therefore the green border?

like image 220
rpsep2 Avatar asked Aug 19 '13 13:08

rpsep2


1 Answers

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.

like image 60
Sparky Avatar answered Oct 04 '22 04:10

Sparky