Validating group of fields with jQuery validate
Let's say I have a form with email and phone fields and I want to check if at least one them is correct. I mean, I'm ok with user entering valid phone and invalid email. Is there a way to do开发者_运维百科 this using jQuery validation plug-in? (I wasn't able to find a set of options to cover all the cases and ended up coding it by hand)
There's a plugin I wrote for validating fields in jQuery which will do what you want rather well.
Warning: I genuinely think this is the best solution for your problem, but don't just take my word for it because I can't be objective.
You can get the plugin here: http://plugins.jquery.com/project/validate-field
To do what you require:
$('#email,#phone').validateField({
notEmpty: function (val) { // if this function returns true, the field must not be empty
return ($('#email:blank,#phone:blank').size() > 1);
},
message: 'Please fill in either the Email or Phone field',
validateOn: '#email,#phone',
validateEvent: 'change'
});
Edit: added validateOn
and validateEvent
to make sure the errors on both objects are cleared when one is filled in.
精彩评论