Angel M.
Angel M.

Reputation: 2742

jQuery validate phone number

I'd like to validate phone number as: (000) 111-1111 I'm using this snippet, which works fine if the user enters only numbers. but if he started with a brackets, all crashes .. I really would need help ...

$("input#phone1,input#phone2").keyup(function() {
        var curchr = this.value.length;
        var curval = $(this).val();
        //var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
        var numericReg = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
        if(!numericReg.test(curval)) {
            $(this).prev('label').append(tag_error + numeric_chars_only + end_tag);
            console.log($(this)+numeric_chars_only);
        }
        if (curchr == 3) {
            $("input#phone1").val("(" + curval + ")" + " ");
        } else if (curchr == 9) {
            $("input#phone1").val(curval + "-");
        }
    });

Upvotes: 0

Views: 4307

Answers (2)

Timothy Owen
Timothy Owen

Reputation: 466

I'd suggest using this:

^(?\d{3})?[- ]?\d{3}[- ]?\d{4}$

It allows (555)555-5555, 5555555555, 555 555 5555, 555-555-5555, (555)-555-5555

ETC.

Upvotes: 2

gdoron
gdoron

Reputation: 150313

I think this is what you need:

/^\(\d{3}\) \d{3}-\d{4}$/

var x = '(000) 111-1111'.replace(/^\(\d{3}\) \d{3}-\d{4}$/, "");
alert(x);​ // alerts empty string. the regular expression worked.

Live DEMO

Upvotes: 3

Related Questions