function checkPhoneNumber(phone) {
var regexp = /^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/i
if (regexp.test(phone) && phone.length > 0) {
return true;
} else {
return false;
}
}
Quick cheat sheet
- Start the expression:
/^
- If you want to require a space, use:
[\s]
or\s
- If you want to require parenthesis, use:
[(]
and[)]
. Using\(
and\)
is ugly and can make things confusing. - If you want anything to be optional, put a
?
after it - If you want a hyphen, just type
-
or[-]
. If you do not put it first or last in a series of other characters, though, you may need to escape it:\-
- If you want to accept different choices in a slot, put brackets around the options:
[-.\s]
will require a hyphen, period, or space. A question mark after the last bracket will make all of those optional for that slot. \d{3}
: Requires a 3-digit number: 000-999. Shorthand for[0-9][0-9][0-9]
.[2-9]
: Requires a digit 2-9 for that slot.(\+|1\s)?
: Accept a “plus” or a 1 and a space (pipe character,|
, is “or”), and make it optional. The “plus” sign must be escaped.- If you want specific numbers to match a slot, enter them:
[246]
will require a 2, 4, or 6.[77|78]
will require 77 or 78. $/
: End the expression
ref: http://stackoverflow.com/questions/14639973/javascript-regex-what-to-use-to-validate-a-phone-number
Leave a comment