The telephone number validator project is the fourth of the five projects in Freecodecamp’s JavaScript Algorithms and Data Structures Certification. The project tasks developers to create a program that receives alphanumeric inputs and checks whether such inputs are valid USA telephone numbers.
This article explains the steps to complete the telephone number validator project. The article is aimed at developers who are currently going through the JavaScript Algorithms and Data Structures Certification Courses. It is also aimed at developers seeking a guide to complete the Telephone Number Validator project challenge on Freecodecamp.
Are you interested in growing your brand through content marketing, check our offerings to see how we can help you by creating quality articles and blog posts for your blogs and websites.
The Telephone Number Validator Challenge
Here is the project challenge as seen on freecodecamp.
“
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.
”
What do you learn by completing the Telephone Number Validator Project?
After completing the telephone number validator project, you will learn the following:
- How to match patterns with regular expressions
- How to test regular expressions using the regex.test() method
How to build a Telephone Number Validator
One of the ways to complete the Telephone Number Validator project is by using Regular Expressions (Regex). Start by matching the first format of valid numbers provided, then expand the regular expressions until all the formats provided in the challenge are matched.
The code
Here is the code that solves this challenge:
function numberChecker (str) {
let regex = /^1?\s?(\d{3}|\(\d{3}\))-?\s?\d{3}-?\s?\d{4}$/gm
return regex.test(str);
}
A detailed explanation of this code block and its regular expressions follows below.
The steps to Write the Code above include the following:
1. Declare a function and pass ‘str’ as its parameter. I called the function, numberChecker. Feel free to assign your function to any descriptive name. This function is the actual program that checks the validity of numbers whenever it is called.
function numberChecker (str) {
}
2. Declare regular expressions to match the first valid format. The first valid format provided in the challenge is:
555-555-5555
To validate all numbers in this format:
- match all numbers that start with 3 consecutive digits with
\d{3}
. (Remember to use the front slash and not the backslash) - match the first hyphen with
–
- match the next 3 consecutive digits after the dash with another
\d{3}
- match the second hyphen with
–
- match the next four digits in a row
\d{4}
This gives us the regex \d{3}-\d{3}-\d{4}
3. Adapt this regex to match the second valid format provided.
(555)555-5555
Observe that the differences between the first format already matched by the regex and the second format of valid numbers include:
a. In the second format [(555)555-5555], the first 3 digits are enclosed within round brackets
b. Secondly, there is no dash (hyphen) after the bracket (between the first and second groups of the consecutive trio of digits).
To match the brackets:
- include a regular expression that tells the validator to match 3 digits without a bracket or three digits with a bracket. This is achieved by adding another match for any 3 consecutive digits that appear in rounded brackets.
The regex to match 3 consecutive digits enclosed in a rounded bracket is \(\d{3}\)
. Remember to add this new regex beside the first match for three consecutive digits [\d{3}]
. Separate both matches with a vertical pipe (|
).
- group both regex together by enclosing them in a rounded bracket
Here is the grouping:
(\d{3}|\(\d{3}\))
- to tell the validator that the dash (hyphen) after this regex grouping is optional, include a question mark after the dash.
(\d{3}|\(\d{3}\))-?
Question marks indicate an optional variable.
The regex at this point looks this way: (\d{3}|\(\d{3}\))-?\d{3}-\d{4}
4. Match the third format of valid numbers
(555) 555-5555
The difference between this format and the previous two formats that have been matched is that there is a space after the parenthesis, before the second set of 3 digits.
To match this space:
- include the regular expression for whitespaces –
\s
- make the whitespaces optional by including a question mark –
\s?
The regex becomes: (\d{3}|\(\d{3}\))-?\s?\d{3}-\d{4}
5. Expand the regex to match the fourth format
555 555 5555
The only peculiar feature of the fourth format of valid numbers is that there is another whitespace after the second set of 3 digits instead of a dash. To match that:
- make the hyphen (which we have matched) optional by adding a question mark to it
-?
With this, the validator will recognize a number with a hyphen as well as one with a whitespace after the second trio of digits.
- Include optional whitespace as well:
-?\s?
The regex becomes:
(\d{3}|\(\d{3}\))-?\s?\d{3}-?\s?\d{4}
Importantly, the regex declared so far also covers the 5th format, 5555555555 since all the properties of this format have been matched.
6. Match the country code in the sixth format
1 555 555 5555
The difference between the 6th format and the first five is that it includes the country code, ‘1’, and whitespace after that. To match this, include an optional figure 1 and an optional whitespace at the beginning of the regex: 1?\s?
This brings the complete regex to:
^1?\s?(\d{3}|\(\d{3}\))-?\s?\d{3}-?\s?\d{4}$
This regex matches all formats
7. Create a variable, regex, and assign the regular expression you wrote to it:
let regex = /^1?\s?(\d{3}|\(\d{3}\))-?\s?\d{3}-?\s?\d{4}$/gm
8. Return the regex.test() method to validate numbers when the function is called: You need to test the regex to ensure that the code works fine. Luckily, JavaScript has an inbuilt method for testing regular expressions – the regex.test
method. Hence:
Return regex.test(str);
The entire code becomes:
function numberChecker (str) {
let regex = /^1?\s?(\d{3}|\(\d{3}\))-?\s?\d{3}-?\s?\d{4}$/gm
return regex.test(str);
}
If you’re in need of high quality technical content, check out our unique offerings and let us do the job for you.
A Breakdown of the Regular Expression Used to Solve the Telephone Number Validator Project
For the sake of clarity, this section contains a breakdown and an explanation of the various parts of the regular expression that solved the telephone number validator challenge.
The regex that solved this challenge is:
let regex = /^1?\s?(\d{3}|\(\d{3}\))-?\s?\d{3}-?\s?\d{4}$/gm
Where:
/^
signifies the start of the regular expression
1?
– this signifies that a valid number may start with figure 1, which is optional. The question mark tells the validator that the figure is optional. This matches the beginning of the last (6th) format.
A question mark signifies an optional variable in a regex.
\s?
– signifies that there may be a whitespace after figure 1 (optional whitespace). Again, this matches the 6th format.
(\d{3}|\(\d{3}\))
– signifies a regex grouping that instructs the validator as follows:
\d{3}
– The numbers may start with 3 consecutive digits.\d
is used to match digits.|
means ‘or’\(\d{3}\)
– The numbers may start with 3 consecutive digits enclosed in a round bracket.- The bracket around these regex signifies the start and end of the group.
-?
after the grouping signifies an optional hyphen after the first 3 digits. This and the grouping earlier described match the first, second, and third formats.
\s?
– signifies another optional whitespace that may appear before the second set of digits (as in the third format).
The \d{3}
after the optional hyphen and whitespace matches the second set of triple digits.
-?\s?
– signifies that the second set of digits may also be followed by an optional dash (hyphen) or whitespace.
\d{4}
– indicates that all formats end with 4 digits. With this, all possible formats are matched.
$/
– signifies the end of the regex
gm
– are two flags:
g
– global – which instructs the regex to match all possible occurrencesm
– a modifier used for multi-line matching
You will Get Better with Regex
Regular expressions may be confusing, especially for beginners. However, some online resources can guide you to write the correct regex syntax for your programs.
A good example is regex101.
You can copy any input you wish to match into regex101, and follow the platform’s suggestions in its ‘quick match panel’. This panel can be found on the right side of the platform.
With such platforms and more practice of regular expressions, you will definitely get better.
Leave a Reply