5

I have jQuery Validation plugin on a page. When someone types the phone number into the form field, I want the validator to only recognize a certain format:

###-###-####

I see this in the JavaScript:

phone_number: {
    required: true,
    number: true 
},

Can I add something there to specify the required format for the phone number? I found something about adding the jQuery Mask plugin, but if I can avoid it, I'd rather not add to the page weight. (Plus...surely there must exist some way to validate only a certain format.)

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • There's already a rule for this called `phoneUS`. It's not for that exact strict format because it also allows `()` and dashes optional, but it only accepts US phone numbers. – Sparky Mar 18 '13 at 17:09
  • We really want only that exact format, so that when the data routes into the CRMs it's formatted the way we want it to display. –  Mar 18 '13 at 17:14
  • I’d strongly urge you to refrain from doing this: On the client-side, it’s best to be flexible with the format you allow. Your CRM requirement is a very weak argument for not doing so: You can still easily transform the given phone number into the desired format on the server-side before passing it on to the CRM. Remember: computers are good at finding patterns in input but humans are most comfortable if they can enter their information in a way they’re used to. – Raphael Schweikert Mar 18 '13 at 17:41
  • Thank you for your input. For a future redesign (coming in abt 6 months) this is something on the plate. But I'm routing this form data into multiple different CRMs, all of which I am learning as-I-go. I have requests from the users of all these CRMs to have the phone numbers formatted a certain way. This is in addition to everything else that I have to do. Best-practices wise, formatting in the CRM is the smartest method. Time-prioritization-for-this-month wise, forcing formatting on the front end is the way I'm going for now. –  Mar 18 '13 at 17:51
  • Ok. Just remember that people who don’t have JavaScript enabled will be able to input any value so there’s some validation you’ll have to do server-side either way… – Raphael Schweikert Mar 18 '13 at 20:16
  • Yes, that's another thing I've told them. They're in triage mode at this point, and as much as it's making my teeth itch, I can't always get the go-ahead for the best-practice solution on this one particular site. (The process we're going through for another site is very reassuring. Building smart and scalable from the get-go. We'll be doing the same thing to this particular headache-of-a-site in half a year.) –  Mar 18 '13 at 20:40

4 Answers4

15

@Sparky's suggestion is good if you are a little flexible, but just in case you want just that format, you can add a custom rule:

$.validator.addMethod('customphone', function (value, element) {
    return this.optional(element) || /^\d{3}-\d{3}-\d{4}$/.test(value);
}, "Please enter a valid phone number");

$(document).ready(function () {
    $("#myform").validate({
        rules: {
            field1: 'customphone'
        }
    });
});

Example: http://jsfiddle.net/kqczf/16/

You can easily make this into a custom class rule. This way you could just add a class to each input that you want to have the rule and possibly omit the rules object from the validate call:

$(document).ready(function () {
    $("#myform").validate();
});

<input type="text" name="field1" id="field1" class="required customphone" />

Example: http://jsfiddle.net/kqczf/17/

Community
  • 1
  • 1
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • Thanks @Andrew - that looks like what I'm trying to do. Do I add that into the document header, and just make sure that it calls out the proper form ID? (And for cases where this is a global include, and I want to add this action to a few different form IDs, can I have multiple form IDs? And for the field1 - does that need to match the field's class name, or id, or both?) –  Mar 18 '13 at 17:23
  • You could use a class rule, I'll update my answer. If you do it for each form, the rule key (`field1`) needs to match up with the field *name*. Sounds like using a class rule is what you want though, I'll update the answer. – Andrew Whitaker Mar 18 '13 at 17:25
  • @Leigh: You can put the `$.validator.addMethod` and $.validator.addClassRules` lines in your document header. Your call to `.validate` should occur when the document is ready. – Andrew Whitaker Mar 18 '13 at 17:29
  • You do not need the `addClassRules` method to simply use this custom rule within `class`. See: http://jsfiddle.net/kqczf/18/ – Sparky Mar 18 '13 at 17:52
  • 1
    @Sparky: Thanks for the tip, I didn't realize it would work without it. – Andrew Whitaker Mar 18 '13 at 17:54
  • You'd need the `addClassRules` method if you wanted to assign a "compound" rule to a class name: http://jsfiddle.net/kqczf/19/ – Sparky Mar 18 '13 at 18:11
6

Simply use the phoneUS rule included in the jQuery Validate plugin's additional-methods.js file.

DEMO: http://jsfiddle.net/c9zy9/

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            phone_number: {
                required: true,
                phoneUS: true
            }
        }
    });

});

Alternatively, instead of including the entire additional-methods.js file, you can just pull out the phoneUS method.

DEMO: http://jsfiddle.net/dSz5j/

$(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");

    $('#myform').validate({ // initialize the plugin
        rules: {
            phone_number: {
                required: true,
                phoneUS: true
            }
        }
    });

});
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • 1
    This isn't exactly what the user wants--the dashes are optional and +1 is also allowed. – Andrew Whitaker Mar 18 '13 at 17:04
  • @AndrewWhitaker, I appreciate that but sometimes the user doesn't even know these rules already exist. – Sparky Mar 18 '13 at 17:07
  • In this case, I wasn't aware that the rule existed, so that you for that. But we do need it to be that very exact format; and for our current purposes, they're telling me that they don't care about non-US phone numbers. (Which I think is going to bite them in the backside, but...there ya go. They've heard my objections, they've given their decision.) –  Mar 18 '13 at 17:17
2

Check out the jQuery Masked Input Plugin. It allows you to mask the input with something like this:

$("#phone_number").mask("999-999-9999");
user1936123
  • 216
  • 2
  • 11
  • Thank you; but I'd like to try and accomplish this without adding any additional plugins. –  Mar 18 '13 at 17:20
0

You should try this, and it works well as per your requirement

jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      phoneUS: true
    }
  }
});
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62