Reputation: 2742
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
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