Phone number validator using JavaScript and HTML

This exercise demonstrates writing a function for a US phone number validator using JavaScript and using it in an HTML input field.

Objective

Check if the entered number is a valid US phone number

Scenario:

The phone number is usually a required field during registration or in the checkout form on an e-commerce website. It is, therefore, necessary to validate the entered phone number to ensure reachability. you can minimize fraud while ensuring that you have a way to contact that customer in the future.

Description

In this exercise, you are required to build a US phone number validator. It will allow to check and validate if that string entered in the input field by the user is a valid US telephone number.

Validate the string as the user types the phone number using the oninput event.

  • If the number is invalid display: Please enter a valid phone number.
  • If the number is valid display: Phone number is valid.

A US phone number can be entered in one of the following ways:

  • 222-222-2222
  • (222) 222-2222
  • (222)222-2222
  • 222 222 2222
  • 2222222222
  • 1 222 222 2222

US phone number is a 10-digit number (excluding special characters) and the first three numbers represent area code. If the country code is provided (the phone number will have 11 digits), you must confirm that the country code is 1. Return true if the string is a valid US phone number; otherwise, return false.

Acceptance criteria

  • 1 (555) 555-5555 -> Phone number is valid
  • (555) 555-5555 -> Phone number is valid
  • 5555555 -> Please enter a valid phone number
  • 2 5555555 -> Please enter a valid phone number

Hints

  • Use regular expression to check the input string for the valid format regex.test(str) to test if the string adheres to the regular expression

Solution


Edit phone_number_validator

Solution walkthrough

  • ^ denotes the beginning of the string.
  • (1\s?)? allows for “1” or “1 ” if there is one.
  • \d{n} checks for exactly n number of digits so \d{3} checks for three digits. 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.
  • [\s\-]? checks for spaces or dashes between the groups of digits.
  • $ denotes the end of the string. In this case the beginning ^ and end of the string $ are used in the regex to prevent it from matching any longer string that might contain a valid phone number (eg. “s 555 555 5555 3”).
  • Lastly, we use regex.test(str) to test if the string adheres to the regular expression, it returns true or false.