开发者

Phone Number Validation Javascript

开发者 https://www.devze.com 2023-03-09 09:53 出处:网络
I want users to allow only phone numbers in following format xxx-xxx-xxxx or xxxxxxxxxx all digits only . Can some one suggest a regular expression t开发者_高级运维o do this ?Something like this:

I want users to allow only phone numbers in following format

xxx-xxx-xxxx or xxxxxxxxxx all digits only . Can some one suggest a regular expression t开发者_高级运维o do this ?


Something like this:

\d{3}-\d{3}-\d{4}|\d{10}


While general phone number validation is a larger problem than what you're trying to solve, I'd do the following:

var targ=phone_number_to_validate.replace(/[^\d]/g,''); // remove all non-digits
if(targ && targ.length===10) {
  // targ is a valid phone number
}

Doing it this way will validate all of the following forms:

xxxxxxxxxx
xxx-xxx-xxxx
(xxx) xxx-xxxx
etc.

Also, to trivially check for a valid U.S. area code, you can use:

if(targ.matches(/^[2-9]\d{2}/)) // targ is a valid area code

Again, this is a trivial check. For something a little more rigorous, see this List of Legal US Area Codes.

See also A comprehensive regex for phone number validation


Use this :

/^(1-?)?(([2-9]\d{2})|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/


var rx=/^\d{3}\-?\d{3}\-?\d{4}$/;
if(rx.test(string)){
//10 diget number with possible area and exhange hyphens
}
else //not


The following regular expression can be used to validate defined and operational (as of 6/2011) telephone area codes within the U.S.:

var area_code_RE=
 '(2(?:0[1-35-9]|1[02-9]|2[4589]|3[1469]|4[08]|5[1-46]|6[0279]|7[068]|8[13])'+
 '|3(?:0[1-57-9]|1[02-9]|2[0139]|3[014679]|47|5[12]|6[019]|8[056])'+
 '|4(?:0[126-9]|1[02-579]|2[3-5]|3[0245]|4[023]|6[49]|7[0589]|8[04])'+
 '|5(?:0[1-57-9]|1[0235-8]|[23]0|4[01]|5[179]|6[1-47]|7[01234]|8[056])'+
 '|6(?:0[1-35-9]|1[024-9]|2[0368]|3[016]|4[16]|5[01]|6[012]|7[89]|8[29])'+
 '|7(?:0[1-4678]|1[2-9]|2[047]|3[1247]|4[07]|5[47]|6[02359]|7[02-59]|8[156])'+
 '|8(?:0[1-8]|1[02-8]|28|3[0-25]|4[3578]|5[06-9]|6[02-5]|7[028])'+
 '|9(?:0[1346-9]|1[02-9]|2[0578]|3[15679]|4[0179]|5[124679]|7[1-35689]|8[0459])'+
 ')';
0

精彩评论

暂无评论...
验证码 换一张
取 消