A short and sweet post about regular expressions for north american phone numbers. For a recent project, I needed to implement HTML5 pattern validation for a text input. This text input will capture a North American phone number. I found many examples that validated for pattern, validating examples like:
- (543) 345 2345
- (143)-643-3456
- 6434552345
- (511)3452345
- 765-345-2345
- (543) 145 6445
- …and so on
but none that also validate conceptually. You may not be aware, but north american phone numbers have certain sequences that are restricted:
- first digit can’t be 1 (this is reserved for optional country code)
- second and third digit can’t both be 1 (which makes sense, a number can’t start with 911, 411, etc since it will trigger those specialty numbers)
- fourth digit can’t be 1
all of the example regex’s I found did not account for this conceptual validation. I created my own that accounts for this. You may want to use this and adjust as needed for your specific needs.
<input type="text" id="phone" name="phone" pattern="[\s\(]*((?!1)\d{1})((?!11)\d{2})[-\s\).,]*((?!1)\d{1})\d{2}[-\s.,]*\d{4}[\s]*" />