FCC Challenge: JS Algorithm: Telephone Number Validator
US Telephone Number Validator
freeCodeCamp Challenge Guide: Telephone Number Validator - Guide - The freeCodeCamp Forum
Regex Problem - Build a Telephone Number Validator
Videos
function telephoneCheck(str) {
var regex = /^(1 *)?(\d( |-)*){10}$/gm;
return regex.test(str);
}It is a very short regex, which checks for a possible 1 at the beginning and checks for ten additional digits. Spaces and dashes are allowed. Only three cases out of thirty failed. I might be able to successfully trick every case eventually, but I am too tired from regex now at this point.
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator
That's a cool challenge. I just passed it with the following:
function telephoneCheck(str) {
return /^(?:1[- ]?)?(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}$/.test(str);
}
I'm not sure if saying "tricking" it is a good way to word this. You should be trying to pass the test. You aren't supposed to trick, you're supposed to learn. 😂 Companies won't be happy with cheating a passing unit test.
Telephone regex validators are only good for exercising your knowledge of regex but are impractical and useless, at best. As a developer, you’d want to store the phone number as only digits (restrict input client side and then sanitize server side). Then, when it comes time to display it, you control the formatting and you’ll get consistent results whereas if you stored the value as it was passed in by a user...Good luck lol! So, speaking as a working full stack developer, well done. 👌