Reputation: 165
I would like a reg ex expression that is in phone number format (XXX)XXX-XXXX ..that can be no more than 10 digits, and does not accept 0 or 1 as the first number.
Right now I have -
/^(?!\(?[0-9]11\)?|\(?1[0-9][0-9]\)?|\(?0[0-9][0-9]?)(\(?\d{3}\)?\s?)(\(?\d{3})(\s?-?\s?)(\d{4})$/;
But it does not work.
Any help with this would be greatly appreciated.
Upvotes: 0
Views: 154
Reputation: 26275
You can use expression:
^\([2-9][0-9]{2}\)[0-9]{3}-[0-9]{4}$
^
Assert position beginning of line.\(
An opening bracket (
.[2-9]
First digit between 2 and 9.[0-9]{2}
Two digits.\)
A closing bracket )
.[0-9]{3}
Three digits.-
A hyphen character.[0-9]{4}
Four digits.$
Assert position end of line.You can test it here.
Upvotes: 2
Reputation: 374
We'll match 3 numbers not starting with 0 or 1 surrounded by parenthesis with \([2-9]\d{2}\)
then 3 numbers alone with \d{3}
then 4 numbers following a dash with -\d{4}
.
Your full expression is /\([2-9]\d{2}\)\d{3}-\d{4}/
const regex = /\([2-9]\d{2}\)\d{3}-\d{4}/;
const valid = '(211)222-3333';
const invalid = '(111)222-3333';
console.log(regex.test(valid));
console.log(regex.test(invalid));
Upvotes: 1