JavaScript: Validate a Phone Number

Introduction

Validating a phone number is an important task in web development to ensure users provide a correctly formatted number. A phone number typically follows specific patterns depending on the country, and it can include digits, spaces, parentheses, hyphens, and a leading country code (e.g., +1). This guide will walk you through writing a JavaScript program to validate a basic phone number using regular expressions (regex).

Problem Statement

Create a JavaScript program that:

  • Accepts a phone number from the user.
  • Validates whether the phone number is in the correct format.
  • Displays whether the phone number is valid or invalid.

Example:

  • Input: "123-456-7890"

  • Output: The phone number is valid.

  • Input: "5555555"

  • Output: The phone number is invalid.

Solution Steps

  1. Initialize the Phone Number String: Accept or define the phone number to validate.
  2. Create a Regular Expression (Regex):
    • Define a regular expression to match common phone number patterns.
  3. Validate the Phone Number:
    • Use the test() method to check if the phone number matches the regex pattern.
  4. Display the Result: Output whether the phone number is valid or invalid.

JavaScript Program

// JavaScript Program to Validate a Phone Number
// Author: https://www.rameshfadatare.com/

function validatePhoneNumber(phoneNumber) {
    // Step 2: Define the regular expression for validating phone numbers
    const phonePattern = /^[+]*[(]?\d{1,4}[)]?[-\s./0-9]*$/;

    // Step 3: Test the phone number against the regex
    if (phonePattern.test(phoneNumber)) {
        console.log("The phone number is valid.");
    } else {
        console.log("The phone number is invalid.");
    }
}

// Example usage
const phoneNumber = "123-456-7890";
validatePhoneNumber(phoneNumber);

Explanation

Step 1: Define the Regular Expression

  • The regular expression used in this program is:

    /^[+]*[(]?\d{1,4}[)]?[-\s./0-9]*$/
    

    This regex matches many common phone number formats:

    • ^[+]*: Allows an optional + for country codes.
    • [(]?\d{1,4}[)]?: Matches an optional area code enclosed in parentheses.
    • [-\s./0-9]*: Matches digits along with optional separators like hyphens, spaces, periods, or slashes.

Step 2: Test the Phone Number

  • The test() method is used to check if the phone number matches the regex pattern. If it does, the phone number is valid; otherwise, it is invalid.

Output Example

The phone number is valid.

Example with Invalid Input

const phoneNumber = "5555555";
validatePhoneNumber(phoneNumber);

Output:

The phone number is invalid.

HTML Example with User Input

You can also validate a phone number using a form input in HTML and JavaScript.

HTML and JavaScript Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Phone Number Validator</title>
</head>
<body>
    <h1>Phone Number Validator</h1>
    <input type="text" id="phoneInput" placeholder="Enter your phone number">
    <button onclick="validatePhoneNumber()">Validate</button>
    <p id="result"></p>

    <script>
        function validatePhoneNumber() {
            const phoneNumber = document.getElementById("phoneInput").value;
            const phonePattern = /^[+]*[(]?\d{1,4}[)]?[-\s./0-9]*$/;

            if (phonePattern.test(phoneNumber)) {
                document.getElementById("result").textContent = "The phone number is valid.";
            } else {
                document.getElementById("result").textContent = "The phone number is invalid.";
            }
        }
    </script>
</body>
</html>

Explanation of HTML Example

  • The user enters a phone number in the input field, and when the "Validate" button is clicked, the validatePhoneNumber() function is called to check if the phone number is valid.
  • The result is displayed in the <p> element with the id="result".

Output in Browser

When the user enters a valid phone number, the message "The phone number is valid." will be displayed. If the phone number is invalid, the message "The phone number is invalid." will appear.

Conclusion

This JavaScript program validates a phone number using regular expressions. The program handles various formats of phone numbers, including those with country codes, spaces, hyphens, and parentheses. You can extend this program further by modifying the regular expression to handle specific country formats or more complex scenarios.

Comments