Michael B
Michael B

Reputation: 1763

Having difficulty validating a US phone number in jQuery - need required and PhoneUS

I'm taking over an existing boondoggle of a project with code that is written all over the place, and I'm having difficulty validating a phone number field with the following rules:

-Required -Conforms to a US Phone number

I've looked all over the jQuery site and have tried multiple implementations of the current code below....

Header Code:

    <script>
  $(document).ready(function(){
    $("#the_form").validate();
  });
  </script>

      <script>
    $(document).ready(function(){
    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");
  </script>

    <script>
    $("#col_5_row_1").rules("add", {
 phoneUS: true
 }
});
    </script>

Input Code:

<input type="text" title="Phone" class="required phoneUS" id="col_5_row_1" name="col_5_row_1">

This validates for "required" but not "phoneUS." If I try validating for required + email, that works too.

I've tried putting the custom rule above the validate function and below it, I've tried without the rules("add") function, and seemingly every combination. I'm stumped.

Any ideas? Thanks a ton.

Upvotes: 2

Views: 5076

Answers (1)

spinon
spinon

Reputation: 10847

So I am not sure why the method does not return the message but it is running. But to show a message you can do something like this:

$(document).ready(
    function()
    {
        $.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");

        $("#the_form").validate(
        {
            rules: { col_5_row_1: { required: true, phoneUS: true } },
            messages: { col_5_row_1: { required: "required", phoneUS: "US format" } }
        });
    });

Here is a working example as well:

http://jsfiddle.net/GcATB/

EDIT: One other thing that just dawned on me is that there is an additional methods file that is an extension for the validator that has this and other methods in there. You should check that out as well instead of writing your own for phoneUS.

http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js

Upvotes: 1

Related Questions