JavaScript Form Validation

In this tutorial we will see how to validate a form using JavaScript. To directly see JavaScript code you can click on Contents table to jump there.



Introduction

As in previous tutorial we have seen how to create a Registration form using HTML, CSS. Now, we are coming one step ahead from that. In this tutorial we will see how to validate a form using simple JavaScript. So, I'am assuming that you know basic JavaScript like how to get any element by its class name and by its Id.
So, Let's start with our HTML Code firstly.


HTML

<html>

<head>
    <title> REGISTRATION FORM </title>
</head>

<body>
    <div class="Registration">
        <h2> REGISTER HERE..</h2>
        <div class="container">
            <form method="" action="" name="student_form" onsubmit="return validate()">
                <img class="avatar" src="I80W1Q0.png" alt="avatar image">
                <br>
                <br>
                <label style="text-align: left;">Full Name:</label><br>
                <input type="text" name="username" placeholder="Name.." id="name" autocomplete="off">
                <br>
                <label>Email:</label> <br>
                <input type="text" name="emailaddress" placeholder="Email Address.." id="email" autocomplete="off">
                <br>
                <label>Date of Birth:</label><br>
                <input type="text" name="DOB" id="date" placeholder="dd/mm/yy" autocomplete="off"><br>
                <br>
                <label>Country: </label> <br>
                <select name="country" id="country" autocomplete="off">
                    <option value="select" disabled selected>--Select Country--</option>
                    <option value="INDIA">INDIA</option>
                    <option value="USA">USA</option>
                    <option value="CANADA">CANDA</option>
                    <option value="UK">UK</option>
                    <option value="ENGLAND">ENGLAND</option>
                </select>
                <br>
                <label>Phone Number:</label><br>
                <input type="tel" name="Phone Number" placeholder="Enter Phone Number.." id="phone" autocomplete="off">
                <br>
                <label>Password: </label> <br>
                <input type="password" name="user password" placeholder="Password" id="password" autocomplete="off">
                <br>
                <label>Confirm Password: </label> <br>
                <input type="password" name="confirm user password" id="confirm_pass" placeholder="Confirm Password"
                    autocomplete="off">
                <br>
                <input type="submit" value="REGISTER">
        </div>
        </form>
    </div>
</body>

</html>

CSS Code

As, in this CSS code I have used internal CSS. So, you must write CSS code inside style tag. And style tag should be inside head tag.

<style>
        * {
            padding0px;
            text-align: center;
        }

        .container {
            padding16px;
        }

        h2 {
            margin-top4px;
            font-family: sans-serif;
            text-align: center;
        }

        .avatar {
            width100px;
            height100px;
            vertical-align: middle;
        }

        .Registration {
            margin: auto;
            width550px;
            margin-top30px;
            margin-bottom30px;
            box-sizing: border-box;
            border1px solid rgba(000.1);
            box-shadow0 5px 10px rgba(000.2);
        }

        input[type=text],
        input[type=tel],
        input[type=email],
        input[type=password],
        input[type=date],
        select {
            width400px;
            padding12px 20px;
            text-align: left;
            margin5px 0px;
            display: inline-block;
            border1px solid blue;
            border-radius5px;
        }

        input[type=Submit] {
            width300px;
            padding14px 20px;
            background-color: #4CAF50;
            border: none;
            cursor: pointer;
            margin-top20px;
            color: #000;
            font-weight: bold;
            font-variant: small-caps;
            border-radius1em;
        }

        input[type=Submit]:hover {
            opacity0.8;
        }

        div label {
            font-weight: bolder;
            padding3px;
            margin0px;
            text-align: left;
        }

        select:focus,
        input[type=tel]:focus,
        input[type=text]:focus,
        input[type=email]:focus,
        input[type=password]:focus,
        input[type=date]:focus {
            border2px solid blue;
        }
    </style>

At Last, here comes the JavaScript code. So, have a look on the code.


JavaScript code
  <script type="text/javascript">
        function validate() {
            var name = document.getElementById("name").value;
            var email = document.getElementById("email").value;
            var phone = document.getElementById("phone").value;
            var country = document.getElementById("country");
            var password = document.getElementById("password").value;
            var confirm_pass = document.getElementById("confirm_pass").value;
            var date = document.getElementById("date").value;

            //Form condition starts here

            if (name.length <= 0 || name == null) {
                alert("Please enter your name.");
                return false;
            }
            if (email.length <= 0) {
                alert("Please enter valid email.");
                return false;
            }
            if (date.length <= 0) {
                alert("Please enter your DOB.")
                return false;
            }
            if (country.value == "select") {
                alert("Please select your country.");
                return false;
            }
            if (phone.length < 10 || phone.length > 10) {
                alert("Enter a valid phone number.")
                return false;
            }
            if (password.length <= 0) {
                alert("Password can't be empty.")
                return false;
            }
            if (password.length < 8) {
                alert("Password should be greater than 8 characters.");
                return false;
            }
            if (confirm_pass <= 0) {
                alert("Please enter confirm password.")
                return false;
            }
            if (password !== confirm_pass) {
                alert("Password Mismatches. Please enter same password as in upper field.");
                return false;
            }
            else {
                window.confirm("Form is validated.")
            }
            return false;
        }
    </script>

One thing to remember here I have used false in every if condition. This is because, when a particular entry is unfilled, return false is used to prevent the submission of the form.

Output:

In the above output, as you can see that I have entered all the fields in form So, it is showing Form is Validated Confirm box. On the other hand, if you left any field empty it will show you an alert box to fill that field. In the next tutorial, we will validate a Registration form using RegEx .


Till then, Keep Coding!

1 Comments

Previous Post Next Post

Contact Form