This is my solution for the fourth JavaScript project along with some commentary and other solutions:
Telephone Number Validator
This was my first attempt. It’s a long and complicated regular expression. It passes all of the tests, but it doesn’t respond correctly for every possible input. For example, 5555555555 5555555555
– two sequences of 10 numbers returns true
instead of false
:
function telephoneCheck(str) {
let regex = /^\d{10}(?!\d)|(^1(-|\s)\d{3}|^\(\d{3}\)|}|^1(-|\s|)\(\d{3}\)|^\d{3})(\s|-|)\d{3}(-|\s)\d{4}/;
return regex.test(str);
}
What I didn’t use in my solution was the ?
which matches either zero or one times. This would’ve helped the situations where sometimes there’s a space and sometimes there’s not, but it’s still valid. The basic solution in the fCC Guide for Telephone Number Validator uses the ?
successfully. The guide has great explanations for this regular expression:
function telephoneCheck(str) {
var regex = /^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\s\-]?\d{4}$/;
return regex.test(str);
}
The intermediate solution in the fCC Guide doesn’t pass all of the tests because it returns true
for 555-5555
and 5555555
. However, it is more comprehensive and returns true for phone numbers like 555.555.5555
and (555)555.5555
using dots instead of dashes or spaces. Instead of pasting it here, I added checking for periods and +1
to the basic solution to make that solution more comprehensive:
function telephoneCheck(str) {
var regex = /^(\+?1\s?)?(\(\d{3}\)|\d{3})[\s-.]?\d{3}[\s-.]?\d{4}$/;
return regex.test(str);
}
This solution on Stack Overflow (Comprehensive Regex for Phone Number Validation) is similar to the intermediate solution in the guide and matches every combination of U.S. phone number. It also fails the fCC tests for 555-5555
and 5555555
by returning true
instead of false
:
function telephoneCheck(str) {
var regex = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/;
return regex.test(str);
}