Skip to content

Instantly share code, notes, and snippets.

@tianmingzuo
Created October 14, 2019 20:27
Show Gist options
  • Select an option

  • Save tianmingzuo/f34c457773cc6ba17355c534457a32b4 to your computer and use it in GitHub Desktop.

Select an option

Save tianmingzuo/f34c457773cc6ba17355c534457a32b4 to your computer and use it in GitHub Desktop.
Telephone Number Validator: Return true if the passed string looks like a valid US phone number. The user may fill out the form field any way they choose as long as it has the format of a valid US number. The following are examples of valid formats for US numbers (refer to the tests below for other variants): 555-555-5555 (555)555-5555 (555) 555…
function telephoneCheck(str) {
// Good luck!
let regex = /^([1]\s?)?(\([0-9]{3}\)|[0-9]{3})(\s|-)?[0-9]{3}(\s|-)?[0-9]{4}$/g;
return regex.test(str);
}
telephoneCheck("555-555-5555");
/*
telephoneCheck("1 555-555-5555")should return true.
telephoneCheck("1 (555) 555-5555")should return true.
telephoneCheck("5555555555")should return true.
telephoneCheck("555-555-5555")should return true.
telephoneCheck("(555)555-5555")should return true.
telephoneCheck("1(555)555-5555")should return true.
telephoneCheck("555-5555")should return false.
telephoneCheck("5555555")should return false.
telephoneCheck("1 555)555-5555")should return false.
telephoneCheck("1 555 555 5555")should return true.
telephoneCheck("1 456 789 4444")should return true.
telephoneCheck("123**&!!asdf#")should return false.
telephoneCheck("55555555")should return false.
telephoneCheck("(6054756961)")should return false
telephoneCheck("2 (757) 622-7382")should return false.
telephoneCheck("0 (757) 622-7382")should return false.
telephoneCheck("-1 (757) 622-7382")should return false
telephoneCheck("2 757 622-7382")should return false.
telephoneCheck("10 (757) 622-7382")should return false.
telephoneCheck("27576227382")should return false.
telephoneCheck("(275)76227382")should return false.
telephoneCheck("2(757)6227382")should return false.
telephoneCheck("2(757)622-7382")should return false.
telephoneCheck("555)-555-5555")should return false.
telephoneCheck("(555-555-5555")should return false.
telephoneCheck("(555)5(55?)-5555")should return false.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment