A hyphen-separated United States phone number can be validated in JavaScript using the following regular expression:
(/^[2-9]\d{2}-\d{3}-\d{4}$/.test('222-333-4444');
Broken down into sections:
^[2-9] The phone number string must begin (^) with a digit between 2 and 9. This is the start of the area code. An area code cannot begin with 0 or 1.
\d{2} The first digit of the area code must be followed by two additional digits.
- The area code must be followed by a hyphen.
d{3} The hyphen after the area code must be followed by three digits. This is the local number prefix.
- The local number prefix must be followed by a hyphen
d{4}$ The local number prefix must be followed by four additional digits and this must end the phone number string ($)
Related Articles:
JavaScript Regular Expressions
JavaScript Regular Expression Special Characters: $ ^
JavaScript Number Validation (Repetition)
JavaScript Regular Expression Backslash
JavaScript Regular Expression Square Brackets