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,692
  • 2
  • 32
  • 43
  • 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
  • 147,333
  • 58
  • 291
  • 367
  • yes, but if the user starts typing 'brackets' the snippet changes the first char into brcket and then all crashes :S I need to prevent to change the bracket if the user enters – Angel M. Mar 29 '12 at 18:01
  • @AngelM. Can you give an example what do you mean? – gdoron Mar 29 '12 at 18:02
  • This does not work if there are no brackets or space or dash, I think OP wanted that too :-) – altschuler Mar 29 '12 at 18:04
  • user start typing in the field: (123 ... end the snippet changes this into ((12) 3 ... – Angel M. Mar 29 '12 at 18:05
  • @altschuler. Then he needs this `/^\(?\d{3}\)? ?\d{3}-?\d{4}$/` – gdoron Mar 29 '12 at 18:06
  • @AngelM. I don't understand your comments. I give up, I hope someone else will understand better. Good luck!! – gdoron Mar 29 '12 at 18:07
  • it is the same ... problem is here: if curchr==3, configure the phone number ... but if the curchr[1] == '(' - it should be recognized and not replaced .. – Angel M. Mar 29 '12 at 18:10
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
  • 6
  • 17