How to Validate a Phone Number Using Javascript (Simple)

Published: 24 March 2023
on channel: Max O'Didily
4,751
35

How to Validate a Phone Number Using Javascript (Simple)

Greetings, today we shall be validating a phone number using Javascript. In this tutorial we look at how to validate the UK format for phone numbers, but this can be applied to any phone number format with a bit of tweaking.

The idea is for this tutorial is to be able to replicate this from memory in a coding exam, so we won't be using a regex pattern for this.

We can validate a phone number in Javascript by checking if the input is a digit or not, checking the length of the input and checking if certain elements of the input are specified digits. Eg, the first digit must be a 0 and the second digit must be a 7.

Javascript phone regexes used in this tutorial:

UK landline phone number regex: /\s*\(?(0[1-6]{1}[0-9]{3}\)?[0-9]{6})\s*/
UK mobile phone number regex: /^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/

Javascript tutorial on how to wait for user input before closing the Javascript console:    • How to Wait for User Input in Javascr...  

Here is the code to do wait for user input before closing the Javascript console: https://pastebin.com/MuMPBUp0

Thanks for watching this Javascript tutorial!

This tutorial is aimed at beginners.

Subscribe to keep notified when I upload?:
https://tinyurl.com/SubMaxODidily

How to Validate a Phone Number Using Javascript