I got a regex from Stack Overflow for phone number validation, but it doesn’t get all of the tests to pass.
The test results are:
telephoneCheck("1 555-555-5555") should return true.
telephoneCheck("1 (555) 555-5555") should return true.
telephoneCheck("1(555)555-5555") should return true.
telephoneCheck("1 555 555 5555") should return true.
telephoneCheck("1 456 789 4444") should return true.
The rest of the tests pass.
I tried to make the space after the parentheses with the three digit state code and the hyphens optional by adding asterisk after each one. Is there a better way to do that?
I changed my code to this after reading the hints here (I haven’t looked at the solutions yet and I’m trying to not look):
function telephoneCheck(str) {
let hasTenDigits = false;
let hasElevenDigits = false;
let startsWithOne = false;
let hasPermittedCharsOnly = false;
let hasCorrectParentheses = false;
const tenDigitRegex = /\d{10}/;
const elevenDigitRegex = /\d{11}/;
const startWithOneRegex = /^(1){1}/;
const permittedCharsRegex = /[0-9\-\(\) ]/;
const correctParenthesesRegex = /^\([0-9]{3}\)$/;
if (str.match(tenDigitRegex)) {
hasTenDigits = true;
}
if (str.match(elevenDigitRegex)) {
hasElevenDigits = true;
}
if (str.match(startWithOneRegex)) {
startsWithOne = true;
}
}
How do I check whether the last two Boolean values are true or not? Are my regular expressions for those alright? What about my regular expressions for the other three tests?
I know I need to return false when even one is false, so that’s not what I’m asking. I’m trying to ask about the regular expressions specifically. What expressions do I need for the last two tests?
let hasPermittedCharsOnly = false;
let hasCorrectParentheses = false;
For these two.
And are the other regular expressions I have alright?