Form Validation using JavaScript HTML and CSS

Form validation using JavaScript is a crucial skill for beginners who want to build interactive and user-friendly web applications. By implementing JavaScript form validation, web developers can ensure that correct and complete data is entered before submission. This JavaScript tutorial demonstrates basic validation techniques, including checking for empty fields and validating phone numbers and email formats using simple JavaScript code.

In this tutorial, we will develop a form in Bootstrap 5 and validate the form using JavaScript before submitting. So, this will be client-side form validation only.

Below is the screenshot of the Form

Form Validation in JavaScript html and css

We will follow the below steps:

  1. Develop a form using HTML and CSS with Bootstrap 5
  2. Write JavaScripts to add validation before submission

javascript validate formWatch YouTube Video

Develop a form using HTML and CSS with Bootstrap 5

We will develop a simple form with Name, Phone and Email fields using Bootstrap 5. You can add the Bootstrap 5 library from a CDN. Let's see the html code given below:


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Form Validation using JavaScript</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <br>
        <h1>Form Validation using JavaScript</h1>
        <form class="form1" action="" method="post">
            <div class="mb-3">
                <label for="name" class="form-label">Name</label>
                <input type="text" class="form-control" name="name" id="name" placeholder="Enter your Name" />
                <div class="showerr" id="nameErr"></div>
            </div>
            <div class="mb-3">
                <label for="phone" class="form-label">Phone</label>
                <input type="text" class="form-control" name="phone" id="phone" placeholder="Enter your Phone" />
                <div class="showerr" id="phoneErr"></div>
            </div>
            <div class="mb-3">
                <label for="email" class="form-label">Email</label>
                <input type="text" class="form-control" name="email" id="email" placeholder="Enter your Email" />
                <div class="showerr" id="emailErr"></div>
            </div>
            <div class="text-center">
                <button type="submit" class="btn btn-primary">
                    Submit
                </button>
            </div>
        </form>
    </body>
</html>

This is a simple form with three fields and a submit button. You can see that for each input, there is a place to display a validation error. We will use them in our JavaScript code. For the name field, it is given below:


<div class="showerr" id="nameErr"></div>

We will add the below stylesheet to this. Just a few basic styles are used.


*{
    box-sizing: border-box;
}
.form1{
    width:40%;
    padding:10px;
    margin:auto;
    border: 1px solid #ebdfdf;
    border-radius: 5px;
}
h1{
    text-align: center;
}
.showerr{
    color:red;
}

The screenshot of the form is given below:

Form Validation in JavaScript html and css

Write JavaScripts to add validation before submission

As soon as the submit button is clicked, we will start validating the inputs. To do this, we will call a JavaScript function, validateForm(), on the onSubmit event of the form. So, first we will add the code below to the form element.


onsubmit="return validateForm()"

So, it will look as given below:


<form class="form1" action="form_submit.html" method="post" onsubmit="return validateForm()">

Write JavaScripts for Validation

We will code for three types of validations:

  1. Empty fields validation
  2. Phone number validation
  3. Email format validation

We will write the code for the JavaScript function validateForm(). We will get the values of the input fields into variables and also, we will use variables to assign the validation errors. Once a validation fails, we will set a flag indicating that some validation failed. The function will return false if any validation fails, so that the form will not be submitted.

Empty field validation

We will check if the input values are empty by checking the length, if the length is zero, we can say no values are entered in the field.


function validateForm(){
    // validate form
    let name = document.getElementById("name").value;
    let phone = document.getElementById("phone").value;
    let email = document.getElementById("email").value;

    let nameErr = document.getElementById("nameErr");
    let phoneErr = document.getElementById("phoneErr");
    let emailErr = document.getElementById("emailErr");

    nameErr.innerHTML = "";
    phoneErr.innerHTML = "";
    emailErr.innerHTML = "";

    let errFlag = false;

    if (name.length == 0){
        nameErr.innerHTML = "Name is Required";
        errFlag = true;
    }

    if (phone.length == 0) {
        phoneErr.innerHTML = "Phone is Required";
        errFlag = true;
    }

    if (email.length == 0) {
        emailErr.innerHTML = "Email is Required";
        errFlag = true;
    }

    if (errFlag){
        return false;
    }
    }

Note that the error flag is initialized as false and it is made true when a validation fails. At the end, we are checking if the error flag is true, then we return false, which means one or more validations failed, so the form will not be submitted.

If users submit the form without entering any field values, the validation error messages will be displayed as below:

Form Validation using JavaScript

Phone Number validation

We will use a regular expression for the phone number validation; it is given below:


let phone_regex = /^[1-9][0-9]{9}$/;

The first digit should be any digit between 1 to 9 and then the remaining 9 digits can be from 0 to 9. Total 10 digits. Then we will use the match() method to verify if the input phone number matches the regular expression. If it does not, we give an error message. See the code below:


if (!phone.match(phone_regex)){
    phoneErr.innerHTML = "Phone must be 10 digit with no leading zero";
    errFlag = true;
}

Similarly, we will use another regular expression for the email and match it with the input email. Accordingly, we will display the email validation message.


email_regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!email.match(email_regex)){
    emailErr.innerHTML = "Email is Invalid";
    errFlag = true;
}  

When all the validations are successful, the form will be submitted. So, we will now write an html file for the form action and we will use action="form_submit.html". Let us create an html file named form_submit.html.


<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Validated Form Submitted</title>
        <link rel="stylesheet" href="style.css">
    </head>

    <body>
        <h1>Validated Form Submitted</h1>

    </body>

</html>
    

Our full JavaScript code for the function will be as given below:


function validateForm(){
    // validate form
    let name = document.getElementById("name").value;
    let phone = document.getElementById("phone").value;
    let email = document.getElementById("email").value;

    let nameErr = document.getElementById("nameErr");
    let phoneErr = document.getElementById("phoneErr");
    let emailErr = document.getElementById("emailErr");

    nameErr.innerHTML = "";
    phoneErr.innerHTML = "";
    emailErr.innerHTML = "";

    let errFlag = false;

    if (name.length == 0){
        nameErr.innerHTML = "Name is Required";
        errFlag = true;
    }

    if (phone.length == 0) {
        phoneErr.innerHTML = "Phone is Required";
        errFlag = true;
    }
    else{
        let phone_regex = /^[1-9][0-9]{9}$/;
        if (!phone.match(phone_regex)){
            phoneErr.innerHTML = "Phone must be 10 digit with no leading zero";
            errFlag = true;
        }
    }

    if (email.length == 0) {
        emailErr.innerHTML = "Email is Required";
        errFlag = true;
    }
    else{
        email_regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if (!email.match(email_regex)){
            emailErr.innerHTML = "Email is Invalid";
            errFlag = true;
        }
    }

    if (errFlag){
        return false;
    }
}

javascript form validationTest the Application

In the browser, run index.html. The form will be displayed. Test for empty values and also enter any values in the phone number and email, for example, just enter "test" and submit the form. You should see the error messages. If you enter valid values for name, phone and email, the form will be submitted.

JavaScript form validation source codeDownload Source Code

You can download the source code from GitHub by clicking on the download button below:

JavaScript tutorialConclusion

In this JavaScript tutorial, we have learned how to validate a form using JavaScript. We validated empty fields, phone number and email. This is fully client-side validation. Remember that we cannot rely on client-side validation alone as someone can bypass client-side validation by disabling JavaScript in the browser. So, server-side validation is also required. You can check the related tutorials to learn how you can validate the same form using server-side scripts in PHP.

Please write your comments/questions in the Comments section below. Your questions, doubts and suggestions are always welcome.

Post a Comment

Save my Name and Email id for future comments