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 ?
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