Skip to content

Instantly share code, notes, and snippets.

@MunimIftikhar
Last active May 10, 2023 13:39
Show Gist options
  • Select an option

  • Save MunimIftikhar/a9ff6940d5281f7b67ee22d8681f7980 to your computer and use it in GitHub Desktop.

Select an option

Save MunimIftikhar/a9ff6940d5281f7b67ee22d8681f7980 to your computer and use it in GitHub Desktop.
freeCodeCamp: Telephone Number Validator

Problem statement

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-5555
555 555 5555
5555555555
1 555 555 5555

For this challenge you will be presented with a string such as 800-692-7753 or 8oo-six427676;laskdjf. Your job is to validate or reject the US phone number based on any combination of the formats provided above. The area code is required. If the country code is provided, you must confirm that the country code is 1. Return true if the string is a valid US phone number; otherwise return false.

Input example #1

"1 555-555-5555"

Expected output #1

true

Input example #2

5555555555

Expected output #2

true

Input example #3

"1 555)555-5555"

Expected output #3

false

Input example #4

"1 456 789 4444"

Expected output #4

true

Solution code

// Solution function
function telephoneCheck(str) {
    // Create a regular expression that matches
    // exactly the valid phone number
    let regex = /^(1\s|1)?(\([0-9]{3}\)|[0-9]{3})[\s|-]?[0-9]{3}[\s|-]?[0-9]{4}$/g;
    // Test the regular expression using test function
    return regex.test(str);
}

// Driver code
console.log(telephoneCheck("27576227382"));

Problem link

freeCodeCamp Telephone Number Validator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment