How To Validate Name With Regular Expression Using JavaScript

How To Validate Name With Regular Expression Using JavaScript

Today I'm starting the JavaScript Validation Series. In this article, I Will inform you about the name validation in JavaScript. 

JavaScript Name Validation

Table of Content

  1. Create Form
  2. Design CSS
  3. 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="text" class="form-control" id="name" name="username" autocomplete="off">
                                            <label for="name" class="form-label">Name</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 with a form that includes JavaScript validation to ensure accurate user input. The structure begins by defining the document type and language. In the head section, crucial details like character encoding and viewport settings are set, alongside links to external resources for styling, including Bootstrap CSS and a custom stylesheet. 

Moving to the body of the page, content is organized using Bootstrap's grid system. The form itself is encapsulated within a card element, providing a visually pleasing container. The card's header proudly displays "Rays Coding :- JavaScript Validation". Inside the form, there's a single input field labeled "Name", followed by areas designated for displaying error and success messages, initially hidden from view.

The form submission button, styled as a prominent Bootstrap primary button, is set to execute a JavaScript function called "validation()" when clicked. This function likely handles the validation logic, ensuring that user inputs meet specified criteria.

Lastly, the page links to an external JavaScript file ("script.js"), presumably containing the validation logic referenced earlier. Overall, this HTML code constructs a user-friendly web page with a form that leverages JavaScript to validate user input, enhancing data accuracy and user experience.

JavaScript Name Validation

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;
    }
    .card
    {
        width: 60%;
        margin: 10px auto;
    }
    .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;
    }

JavaScript Name Validation

Validation Code

    function validation()
    {
        // get the input box value
        let inputVal = document.getElementById('name').value.trim();
        // Regex value
        let nameRegex = /^[a-zA-Z\s]+$/;
        // Conditions
        if (inputVal === '')
        {
            document.getElementById('error').innerText = "Please enter the name.";
            document.getElementById('errorRow').style.display = "block";
            hideError();
            return false;
        }
        else if (inputVal.length < 3)
        {
            document.getElementById('error').innerText = "Please enter a valid name with at least 3 characters.";
            document.getElementById('errorRow').style.display = "block";
            hideError();
            return false;
        }
        else if (!nameRegex.test(inputVal))
        {
            document.getElementById('error').innerText = "Please enter a valid name with only alphabetic characters.";
            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);
    }

JavaScript Name Validation

This JavaScript code defines a function named validation(), which serves to validate user input in a form. Firstly, it retrieves the value entered in the input box labeled "name". Then, it defines a regular expression (nameRegex) to match only alphabetic characters and spaces. The function then proceeds to validate the input based on several conditions:

If the input is empty, it displays an error message prompting the user to enter a name and shows the error message area (errorRow), before hiding it after a brief delay using the hideError() function.

If the input's length is less than 3 characters, it prompts the user to enter a name with at least 3 characters and displays the error message.

If the input contains characters other than alphabetic characters or spaces, it displays an error message indicating that only alphabetic characters are allowed.

If none of the above conditions are met, it assumes the input is valid and displays a success message with the entered name (inputVal) in a success message area (successRow).

Additionally, there's a helper function named hideError() that hides the error message area (errorRow) after a 5-second delay.

This JavaScript code provides client-side validation for the form's "name" input field, ensuring that the entered data meets specified criteria and providing feedback to the user accordingly.

JavaScript Name Validation

Post a Comment

Previous Post Next Post

Recent in Technology