0

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}
  }
});
nolabel
  • 1,147
  • 3
  • 18
  • 26

2 Answers2

0

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}
  }
});
Pramendra Gupta
  • 14,667
  • 4
  • 33
  • 34
  • 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 Sep 03 '10 at 00:16
0

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);
    }
}
Community
  • 1
  • 1
nolabel
  • 1,147
  • 3
  • 18
  • 26