Phone Number Validation Javascript

后端 未结 5 1072
情深已故
情深已故 2020-12-09 21:40

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 to do this ?

5条回答
  •  萌比男神i
    2020-12-09 21:46

    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

提交回复
热议问题