How to extending Jquery validatation to validate 2 of 3 required phone number?
I am using jQuery Validation and here is the extension that I am using to validate US phone number.
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
This works great, but what if I only want to validate 2 of the 3 numbers.
For an example, I have
Home Phone: <input name="h" ...>
Work Phone: <input name="w" ...>
Cell Phone: <input nam开发者_运维百科e="c" ...>
$('form').validate({
rules: {
h: {phoneUS: true},
w: {phoneUS: true},
c: {phoneUS: true}
}
});
use class in input fields
Home Phone: <input name="h" class="phones">
Work Phone: <input name="w" class="phones">
Cell Phone: <input name="c" class="phones">
and change your jquery
$('.phones').validate({
rules: {
h: {phoneUS: true},
w: {phoneUS: true},
c: {phoneUS: true}
}
});
Found an answer here:
jQuery Validate - require at least one field in a group to be filled
Also, before I found this I did come up with my own solution that works.
h: {
phoneUS: true,
required: function(element) {
return ($('input.phones:blank').length >= 2);
}
},
c: {
phoneUS: true,
required: function(element) {
return ($('input.phones:blank').length >= 2);
}
},
w: {
phoneUS: true,
required: function(element) {
return ($('input.phones:blank').length >= 2);
}
}
精彩评论