Validating Phone Numbers Using JavaScript

Validating Phone Numbers Using JavaScript

Learn how to Validate contact numbers using JavaScript in our latest blog post. Dive into the basics of contact number validation techniques to ensure data integrity and enhance user experience on your website.

Validating Phone Numbers Using JavaScript

Table of Content

  • Create Form
  • Design CSS
  • Validation Code

Create Form


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title></title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="container mt-5">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-header wrapper">
                            <h3 class="title">Rays Coding :- JavaScript Validation</h3>
                        </div>
                        <div class="card-body">
                            <form action="" method="post">
                                <div class="row">
                                    <div class="col-lg-12">
                                        <div class="mb-3 field">
                                            <input type="number" class="form-control" id="contact" name="usercontact"  autocomplete="off">
                                            <label for="contact" class="form-label">Contact</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="row error-row" id="errorRow" style="display: none;">
                                    <div class="col-lg-12">
                                        <div class="mb-3 field">
                                            <div class="alert alert-danger" id="error"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row success-row" id="successRow" style="display: none;">
                                    <div class="col-lg-12">
                                        <div class="mb-3 field">
                                            <div class="alert alert-success" id="success"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-lg-12">
                                        <div class="field">
                                            <button type="button" class="btn btn-primary w-100" onclick="validation()">SUBMIT</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script src="script.js"></script>
    </body>
    </html>


This HTML code creates a web page for a JavaScript validation form. It begins with the standard HTML5 doctype declaration and sets the language to English. The meta tags define character set and viewport settings. The page includes Bootstrap 5 CSS framework and a custom CSS file named "style.css" for styling.

Within the body, there's a container with a card layout, styled using Bootstrap classes. Inside the card, there's a form for user input, specifically for a contact number. The input field is of type "number" with a corresponding label. Below the input field, there are placeholders for error and success messages, which are initially hidden.

Validating Phone Numbers Using JavaScript

The form has a submit button with an onclick event calling a JavaScript function named "validation()". This function is expected to handle the form validation logic but isn't defined in the provided code snippet. The JavaScript file "script.js" is included at the end of the body, suggesting that the validation logic is likely implemented there.

Design CSS


    @import url('https://fonts.googleapis.com/css?family=Poppins:400,500,600,700&display=swap');
    *
    {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Poppins', sans-serif;
    }
    body
    {
        background: aliceblue;
    }
    .card
    {
        width: 60%;
        margin: 10px auto;
        background: #fff;
    }
    .wrapper
    {
        background: #fff;
        border-radius: 15px;
        box-shadow: 0px 15px 20px rgba(0,0,0,0.1);
        background: linear-gradient(-135deg, #c850c0, #4158d0);
    }
    .title
    {
        color: #fff;
        text-shadow:  0 0 10px #fff;
        text-align: center;
    }
    .field
    {
        height: 50px;
        width: 100%;
        margin-top: 20px;
        position: relative;
    }
    .field input.form-control
    {
        height: 100%;
        width: 100%;
        box-shadow: none;
        outline: none;
        font-size: 17px;
        padding-left: 20px;
        border: 1px solid lightgrey;
        border-radius: 25px;
        transition: all 0.3s ease;
    }
    .field input.form-control:focus,
    .field input.form-control:valid
    {
    border-color: #4158d0;
    }
    .field label
    {
        position: absolute;
        top: 50%;
        left: 20px;
        color: #999999;
        font-weight: 400;
        font-size: 17px;
        pointer-events: none;
        transform: translateY(-50%);
        transition: all 0.3s ease;
    }
    .field input.form-control:focus ~ label,
    .field input.form-control:valid ~ label
    {
        top: 0%;
        font-size: 16px;
        color: #4158d0;
        background: #fff;
        transform: translateY(-50%);
    }
    .field button
    {
        border: none;
        outline: none;
        background: linear-gradient(-135deg, #c850c0, #4158d0);  
    }
    .error-row
    {
        display: none;
    }


This CSS code defines the styling for a web page, likely accompanying the HTML form from the previous snippet. It begins by importing the Google Font "Poppins" and setting it as the default font for the entire document. The universal selector (*) is then used to reset margins, padding, and box-sizing for all elements to ensure consistent rendering across different browsers.

The body background is set to "aliceblue", providing a light blue backdrop for the page content. The ".card" class is styled to create a card-like container with a width of 60% of the viewport, centered horizontally with a margin of 10 pixels from the top. It has a white background and some box-shadow to give it a subtle elevation effect.

Validating Phone Numbers Using JavaScript
The ".wrapper" class further styles an inner container within the card, giving it a gradient background transitioning from a pinkish color to a blueish one. This inner wrapper adds visual appeal to the card. The ".title" class styles the title within this wrapper, giving it a white color with a text shadow effect and centering it within the wrapper.

The ".field" class styles the form input fields and labels. Each field has a height of 50 pixels and a position of relative to allow for positioning of the label relative to the input. The input fields have specific styling such as padding, border, border-radius, and transition effects for smoother user interactions. Labels are positioned absolutely within the field and transitioned for smooth movement when the input is focused or contains a valid value.

Lastly, the ".error-row" class sets the display to "none", likely intended to hide any error messages initially until triggered by JavaScript validation logic.

Validation Code

   
    function validation()
    {
        // get the input box value
        let inputVal = document.getElementById('contact').value;
        console.log(inputVal);
       
        // Regex value
        let numberRegex = /[0-9]+/;
        // Conditions
        if (inputVal === '')
        {
            document.getElementById('error').innerText = "Please enter the contact number.";
            document.getElementById('errorRow').style.display = "block";
            hideError();
            return false;
        }
        else if (inputVal.length != 10)
        {
            document.getElementById('error').innerText = "Contact number should be 10 digits.";
            document.getElementById('errorRow').style.display = "block";
            hideError();
            return false;
        }
        else if (!numberRegex.test(inputVal))
        {
            document.getElementById('error').innerText = "Please enter a valid contact number.";
            document.getElementById('errorRow').style.display = "block";
            hideError();
            return false;
        }
        else
        {
            document.getElementById('success').innerText = 'You Enter ' + inputVal;
            document.getElementById('successRow').style.display = "block";
            return true;
        }
    }
    // Hide error message
    function hideError()
    {
        setTimeout(function() {
            document.getElementById('errorRow').style.display = "none";
        }, 5000);
    }

This JavaScript code provides form validation functionality for the contact number input field in the HTML form.

The validation() function is triggered when the user clicks the submit button. It begins by retrieving the value entered in the input field with the ID "contact". This value is stored in the variable inputVal, which is logged to the console for debugging purposes.

Validating Phone Numbers Using JavaScript
Next, a regular expression numberRegex is defined to match one or more digits (0-9). This regex is used to validate that the input consists only of numeric characters.

The function then checks several conditions:


  1. If the input value is empty, it displays an error message prompting the user to enter a contact number.
  2. If the input value's length is not equal to 10 digits, it displays an error message indicating that the contact number should be exactly 10 digits long.
  3. If the input value does not match the number regex, it displays an error message stating that the contact number should contain only numeric digits.
  4. If none of the above conditions are met, it displays a success message indicating that the input value is valid.
The hideError() function is called to hide the error message after a delay of 5 seconds (5000 milliseconds) using setTimeout(). This function sets the display property of the error message row to "none", effectively hiding it from the user interface.

Validating Phone Numbers Using JavaScript


Post a Comment

Previous Post Next Post

Recent in Technology