0

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 + "-");
        }
    });
Angel M.
  • 2,552
  • 2
  • 31
  • 42
  • Where are `tag_error`, `numeric_chars_only`, and `end_tag` defined? – Ethan Brown Mar 29 '12 at 18:05
  • 1
    this is only alert fo user .. – Angel M. Mar 29 '12 at 18:06
  • Hiya! hmm I have created this for you - http://jsfiddle.net/5NCQg/18/ Can you show us a demo how do you mean onkeyup validation? :) Also this http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery **OR** http://stackoverflow.com/questions/6960596/example-of-a-regular-expression-in-jquery-for-phone-numbers might give you better Idea! Cheers – Tats_innit Mar 29 '12 at 18:26

2 Answers2

3

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

gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
2

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.

Timothy Owen
  • 466
  • 1
  • 5
  • 17