Form Validation JavaScript

Afroj MansooriAfroj Mansoori
3 min read

Create a form with proper form validation using JavaScript (name, email, phone number, password, age, gender, date, color picker)

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<h1 class="text-white text-center font-weight-bold bg-success" style="font-size: 55px;"> validation form</h1>

    <div class="container"><br>

        <div class="col-lg-6 m-auto d-block">

            <form action="#" onsubmit="return validation()" class="bg-light">

                <div class="form-group">
                    <label for="user" class="font-weight-bold"> Username: </label>
                    <input type="text" name="user" class="form-control" id="user" autocomplete="off">
                    <span id="username" class="text-danger font-weight-bold"> </span>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold"> Password: </label>
                    <input type="text" name="pass" class="form-control" id="pass" autocomplete="off">
                    <span id="passwords" class="text-danger font-weight-bold"> </span>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold"> Confirm Password: </label>
                    <input type="text" name="conpass" class="form-control" id="conpass" autocomplete="off">
                    <span id="confrmpass" class="text-danger font-weight-bold"> </span>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold"> Mobile Number: </label>
                    <input type="text" name="mobile" class="form-control" id="mobileNumber" autocomplete="off">
                    <span id="mobileno" class="text-danger font-weight-bold"> </span>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold"> Email: </label>
                    <input type="text" name="email" class="form-control" id="emails" autocomplete="off">
                    <span id="emailids" class="text-danger font-weight-bold"> </span>
                </div>
                <div class="clr">
                    <label class="clr-pick"> Pick your favorate-color: </label>
                    <input type="color" name="clr-pick" class="form-control" id="color"  ><br>
                </div>
                <div class="date">
                    <label class="date"> Date: </label>
                    <input type="date" name="date" class="form-control" id="date"  ><br>
                </div>

                <input type="submit" name="submit" value="submit" class="btn btn-success"     autocomplete="off">


            </form><br><br>


        </div>
    </div>



    <script type="text/javascript">


        function validation(){

            var user = document.getElementById('user').value;
            var pass = document.getElementById('pass').value;
            var confirmpass = document.getElementById('conpass').value;
            var mobileNumber = document.getElementById('mobileNumber').value;
            var emails = document.getElementById('emails').value;





            if(user == ""){
                document.getElementById('username').innerHTML =" ** Please fill the username field";
                return false;
            }
            if((user.length <= 2) || (user.length > 20)) {
                document.getElementById('username').innerHTML =" ** Username lenght must be between 2 and 20";
                return false;    
            }
            if(!isNaN(user)){
                document.getElementById('username').innerHTML =" ** only characters are allowed";
                return false;
            }







            if(pass == ""){
                document.getElementById('passwords').innerHTML =" ** Please fill the password field";
                return false;
            }
            if((pass.length <= 5) || (pass.length > 20)) {
                document.getElementById('passwords').innerHTML =" ** Passwords lenght must be between  5 and 20";
                return false;    
            }


            if(pass!=confirmpass){
                document.getElementById('confrmpass').innerHTML =" ** Password does not match the confirm password";
                return false;
            }



            if(confirmpass == ""){
                document.getElementById('confrmpass').innerHTML =" ** Please fill the confirmpassword field";
                return false;
            }




            if(mobileNumber == ""){
                document.getElementById('mobileno').innerHTML =" ** Please fill the mobile NUmber field";
                return false;
            }
            if(isNaN(mobileNumber)){
                document.getElementById('mobileno').innerHTML =" ** user must write digits only not characters";
                return false;
            }
            if(mobileNumber.length!=10){
                document.getElementById('mobileno').innerHTML =" ** Mobile Number must be 10 digits only";
                return false;
            }



            if(emails == ""){
                document.getElementById('emailids').innerHTML =" ** Please fill the email idx` field";
                return false;
            }
            if(emails.indexOf('@') <= 0 ){
                document.getElementById('emailids').innerHTML =" ** @ Invalid Position";
                return false;
            }

            if((emails.charAt(emails.length-4)!='.') && (emails.charAt(emails.length-3)!='.')){
                document.getElementById('emailids').innerHTML =" ** . Invalid Position";
                return false;
            }
        }

    </script>

</body>
</html>
function clearErrors(){

    errors = document.getElementsByClassName('formerror');
    for(let item of errors)
    {
        item.innerHTML = "";
    }


}
function seterror(id, error){
    //sets error inside tag of id 
    element = document.getElementById(id);
    element.getElementsByClassName('formerror')[0].innerHTML = error;

}

function validateForm(){
    var returnval = true;
    clearErrors();

    //perform validation and if validation fails, set the value of returnval to false
    var name = document.forms['myForm']["fname"].value;
    if (name.length<5){
        seterror("name", "*Length of name is too short");
        returnval = false;
    }

    if (name.length == 0){
        seterror("name", "*Length of name cannot be zero!");
        returnval = false;
    }

    var email = document.forms['myForm']["femail"].value;
    if (email.length>15){
        seterror("email", "*Email length is too long");
        returnval = false;
    }

    var phone = document.forms['myForm']["fphone"].value;
    if (phone.length != 10){
        seterror("phone", "*Phone number should be of 10 digits!");
        returnval = false;
    }

    var password = document.forms['myForm']["fpass"].value;
    if (password.length < 6){

        // Quiz: create a logic to allow only those passwords which contain atleast one letter, one number and one special character and one uppercase letter
        seterror("pass", "*Password should be atleast 6 characters long!");
        returnval = false;
    }

    var cpassword = document.forms['myForm']["fcpass"].value;
    if (cpassword != password){
        seterror("cpass", "*Password and Confirm password should match!");
        returnval = false;
    }

    return returnval;
}

0
Subscribe to my newsletter

Read articles from Afroj Mansoori directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Afroj Mansoori
Afroj Mansoori