views:

20

answers:

2

Hello,

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 name="c" ...>


$('form').validate({
  rules: {
    h: {phoneUS: true},
    w: {phoneUS: true},
    c: {phoneUS: true}
  }
});
A: 

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}
  }
});
JapanPro
@JapanPro, how does this required at least 2 of the 3 phone numbers being entered? One of these condition has to be true: home+work or work+cell or home+cell combination.
nolabel
A: 

Found an answer here:

http://stackoverflow.com/questions/1300994/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);
    }
}
nolabel