DEV Community

Randy Rivera
Randy Rivera

Posted on • Updated on

Validating Phone Numbers with JavaScript

  • Here they want us to return true if the passed string looks like a valid US phone number. The person can fill out the form any way they choose as long as it has the valid format for a US Number.
  • The person may fill out the form field any way they want as long as it has the format of a valid US number. The following are examples of valid formats for US numbers.
555-555-5555
(555)555-5555
(555) 555-5555
555 555 5555
5555555555
1 555 555 5555
Enter fullscreen mode Exit fullscreen mode
  • Code:
function numberCheck(str) {
  return true;
}

numberCheck("555-555-5555");


Enter fullscreen mode Exit fullscreen mode
  • Answer:
//   1- ^ beginning of the string.
//   2- (1\s?)? allows for "1" or "1 " if there is one.
//   3- \d{n} checks for exactly n number of digits so \d{3}
//   checks for three digits
//   4. - x|y checks for either x or y so (\(\d{3}\)|\d{3}
//   checks for either three digits surrounded by parentheses or three digits by themselves with no parentheses
//   5. [\s\-]? checks for spaces or dashes between the groups of digits.
//   6. $ end of the string

function numberCheck(str) {
  const regex = /^(1\s?)?(\d{3}|\(\d{3}\))[\s\-]?\d{3}[\s\-]?\d{4}$/
  return regex.test(str)
}

numberCheck("1 555-555-5555"); will display true
Enter fullscreen mode Exit fullscreen mode

“Freecodecamp.org.” Edited by Quincy Larson, Telephone Number ValidatorPassed, Quincy Larson, 2014, www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator.

Top comments (0)