Back to all resources
validation
regular expression
event handling

Validation - Phone

By Jared Malan
This JavaScript code defines a function validNum that checks if a given phone number matches a specific format using a regular expression. The function takes a single argument, phoneNumber, and returns true if the phone number matches the pattern defined by the regular expression, otherwise it returns false.

The regular expression used (/^(\+0?1\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/) checks for a phone number that:

  • Optionally starts with '+1' or '1' with possible zero and space after the plus.
  • Follows with an area code that might be enclosed in parentheses.
  • The area code is followed by a three-digit block, and then a four-digit block.
  • The blocks can be separated by spaces, dots, or hyphens.

Additionally, an event listener is attached to an HTML element with the #phone-el. This listener triggers on the "blur" event, which occurs when the element loses focus. When triggered, it retrieves the value of the input, checks if it is a valid phone number using the validNum function, and if not valid, a placeholder for error handling is provided where actual error handling code should be implemented.