Form validation in javascript and store Form data in LocalStorage


In the earlier post we have learned how to create html forms and also discussed the importance of forms in web development. Today we will learn how to perform form validation using javascript.

What is form validation

Form validation is most important part in web development. A form can cause the website from being hacked or improper form validation can cause of security vulnerabilities. Form validation can perform at front-end side as well as at back-end side. In this tutorial we are learning form validation in front-side using javascript.

How it works

Sometimes users submit forms with empty fields that are required for data process. In this case important data skipped from the form and we usually gets unnecessary data that is not valuable without these important fields. So in every form some fields are required, so for this purpose we write some code for form validation.

Our form data must go through from that code to check that form has required data in it while submitting the form. HTML also support an attribute named "required" for those fields but this method is not very useful now a days. Everyone have easy access to the developer tools to remove those attribute and submit empty form which is not our requirement.

Usually form data is used to store in database but sometimes data needs to store in local storage for fast processing. We have used local storage for data storage if it is filled properly without any error. If any of the field is skipped then we will also show an array of errors for required fields. Use the following code for this purpose and enjoy coding.

HTML

Following HTML code will display the form in web page and for validation purpose we've used javascript.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        fieldset{
            width: 40%;
            margin: auto;
        }
        table{
            width: 100%;
        }
    </style>
</head>
<body>

    <fieldset>
        <legend>
            Fill your Details
        </legend>
        <form id="person-form">
            <table>
                <tbody>
                    <tr>
                        <td colspan="2"><label for="">Name*</label></td>
                        <td><input autocomplete="off" name="name" type="text"></td>
                    </tr>
                    <tr>
                        <td colspan="2"><label for="">Email*</label></td>
                        <td><input autocomplete="off" name="email" type="email"></td>
                    </tr>
                    <tr>
                        <td colspan="2"><label for="">Gender*</label></td>
                        <td>
                            <select name="gender" id="">
                                <option value="">Select</option>
                                <option value="male">Male</option>
                                <option value="female">Female</option>
                                <option value="others">Others</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2"><label for="">City*</label></td>
                        <td><input autocomplete="off" name="city" type="text"></td>
                    </tr>
                </tbody>
            </table>
            <input type="submit" name="submit" value="Send">
        </form>
        <ul id="err-list"></ul>
     </fieldset>

     <script src="assets/js/forms.js"></script>
    
</body>
</html>

Javascript

Here is some javascript code for functional code in "forms.js" file

document.getElementById("person-form").addEventListener('submit', function (e) {
    e.preventDefault();
    var ul = document.getElementById('err-list');

    ul.innerHTML = '';

    var errList = [];

    if (this.name.value == '') {
        errList.push('Name field is required.');
    }
    if (this.email.value == '') {
        errList.push('Email field is required.');
    }
    if (this.gender.value == '') {
        errList.push('Gender field is required.');
    }
    if (this.city.value == '') {
        errList.push('City field is required.');
    }

    // To generate error list dynamically
    for (var i = 0; i < errList.length; i++) {
        var err = errList[i];
        var li = document.createElement('li');
        li.appendChild(document.createTextNode(err));
        ul.appendChild(li);
    }
    
    var formData = {
        "name" : this.name.value,
        "email" : this.email.value,
        "gender" : this.gender.value,
        "city" : this.city.value
    };

    // To store data in local storage
    if (errList == ''){
        localStorage.setItem('formData', JSON.stringify(formData));
    }

});

That's all and here is the preview in web page

form-validation-in-javascript


Tipu

about the author

Tipu is web developer from Pakistan. He is very talented in developing websites in wordpress and multiple frameworks in php.

other posts by Tipu
View all Posts By Tipu

No Comments Yet!

Leave a Comment  

Your email address will not be published. Required fields are marked *