How to validate Input form using Javascript

Validate the Input(Registration and Login) form using Javascript. It’s really important to get valid data as per types of input. below are some Java Script functions and code that will help to validate input fields like Password, Username, PhoneNumber.

What is form validation?

Form validation is a process that checks whether a user has filled the form correctly before it’s sent to the server. When a user enters a value into an input field and hits the submit button this data will directly send to the server and then the database. If this data is not valid data It can be harmful for the entire application.

So We can validate the data without sending it to the server. below are some examples to validate input fields or forms in JavaScript.

How to validate Input form using Javascript?

It is important to validate the form submitted by the user because it can have inappropriate values, so validation is a must to authenticate the user. Javascript provides a facility to validate the form on the client-side so data processing will be faster than server-side validation.

Validate UserName(Input) in Javascript.

In javascript input validation is also called data validation it is for this to testing of any proper input supplied by the user. In this data on the client’s computer validate it before sending it to the webserver.

Steps

  • Take input from the user
  • Check the conditions
  • It should not be empty
  • It contains only characters A-Z, a-z.

Program to validate Username (input) in JS

<html>
<head>
    <title>Username validation</title>
<script type="text/javascript">
function printError(elemId, hintMsg) {
    document.getElementById(elemId).innerHTML = hintMsg;
} 
function validateForm() { 
    var name = document.contactForm.name.value;
    
    // Defining error variables with a default value
    var nameErr = true;
    
    // Validate name
    if(name == "") {
        printError("nameErr", "Please enter your name");
    } else {
        var regex = /^[a-zA-Z\s]+$/;                
        if(regex.test(name) === false) {
            printError("nameErr", "Please enter a valid name");
        } else {
            printError("nameErr", "");
            nameErr = false;
        }
    }
    if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {
       return false;
    } else {
        // Creating a string from input data for preview
        var dataPreview = "You've entered the following details: \n" +
                          "Full Name: " + name + "\n" +
                        
        alert(dataPreview);
    }
};
</script>
</head>
<body>
    <style>
    body {
    font-size: 16px;
    background: #f9f9f9;
    font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
}

form {
    width: 300px;
    background: #fff;
    padding: 15px 40px 40px;
    border: 1px solid #ccc;
    margin: 50px auto 0;
    border-radius: 5px;
}

input, select {
    border: 1px solid #ccc;
    padding: 10px;
    display: block;
    width: 100%;
    box-sizing: border-box;
    border-radius: 2px;
}

.error {
    color: red;
    font-size: 90%;
}
input[type="submit"] {
    font-size: 110%;
    font-weight: 100;
    background: #006dcc;
    border-color: #016BC1;
    box-shadow: 0 3px 0 #0165b6;
    color: #fff;
    margin-top: 10px;
    cursor: pointer;
}
input[type="submit"]:hover {
    background: #0165b6;
</style>
<form name="contactForm" onsubmit="return validateForm()"  method="post">
    <h2>Form</h2>
    <div class="row">
        <label>User Name</label>
        <input type="text" name="name">
        <div class="error" id="nameErr"></div>
    </div>
    <div class="row">
        <input type="submit" value="Submit">
    </div>
</form>
</body>
</html

Output

In this way, we learned validation in Username in Javascript.

Validate Password Field in JS.

In Javascript there are parameters used for the password validation in any form it should be of only alphabet used or it should be of any specific length of characters.

Steps

  • Take input from the user
  • Check the input conditions                                                                                                                                                                    1. Contains only alphabet

2. Should be of specific length

3.At least one upper case

Program to validate password field in JS

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Password Validation</title>
</head>
<body>
    <script>
        function validatepassword(){
var pass= document.getElementById("pass1").value;
if (/[a-z]/.test(pass) && /\d/.test(pass) && pass.length >= 8 && pass.length <= 15)
{
    document.getElementById("p1prompt").innerHTML=("valid " + "&#10004");
    document.getElementById("p1prompt").style.color="green";
    return true;
}
else {
    document.getElementById("p1prompt").style.color="red";
    document.getElementById("p1prompt").innerHTML=("at least 8 characters containing a lower case");
    return false;
}
}

    </script>
    Password : <input type="password" id="pass1">
<p id="p1prompt"></p>
<button onclick='validatepassword()' type="button">Validate</button>
</body>
</html>

Output

In this way, we learned password validation in JS.

Validate email field in JS.

In Javascript email validation is part of authenticating on HTML form, email is a string of ASCII characters divided into two parts using @ string.

Steps

  • Take  input from the user
  • Check the conditions of the email validation

Program to validate email using Javascript

<!DOCTYPE html>
<html>
<head>
<title>Email validation JS</title>
<script>
// Defining a function to display error 
function printError(elemId, hintMsg) {
    document.getElementById(elemId).innerHTML = hintMsg;
}

// Defining a function to validate form 
function validateForm() {
    // Retrieving the values of form elements 
    var email = document.contactForm.email.value;
    
  // Defining error variables with a default value
    var emailErr = true;
    
    
    // Validate email address
    if(email == "") {
        printError("emailErr", "Please enter your email address");
    } else {
        // Regular expression for basic email validation
        var regex = /^\S+@\S+\.\S+$/;
        if(regex.test(email) === false) {
            printError("emailErr", "Please enter a valid email address");
        } else{
            printError("emailErr", "");
            emailErr = false;
        }
    }
    
    // Prevent the form from being submitted if there are any errors
    if(( emailErr ) == true) {
       return false;
    } else {
        // Creating a string from input data for preview
        var dataPreview = "You've entered the following details: \n" +
                          "Email Address: " + email + "\n" +
                          
        // Display input data in a dialog box before submitting the form
        alert(dataPreview);
    }
};
</script>
<style>
    body {
    font-size: 16px;
    background: #f9f9f9;
    font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
}

form {
    width: 300px;
    background: #fff;
    padding: 15px 40px 40px;
    border: 1px solid #ccc;
    margin: 50px auto 0;
    border-radius: 5px;
}

input, select {
    border: 1px solid #ccc;
    padding: 10px;
    display: block;
    width: 100%;
    box-sizing: border-box;
    border-radius: 2px;
}

.error {
    color: red;
    font-size: 90%;
}
input[type="submit"] {
    font-size: 110%;
    font-weight: 100;
    background: #006dcc;
    border-color: #016BC1;
    box-shadow: 0 3px 0 #0165b6;
    color: #fff;
    margin-top: 10px;
    cursor: pointer;
}
input[type="submit"]:hover {
    background: #0165b6;
</style>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()"  method="post">
    <h2>Application Form</h2>
   
    <div class="row">
        <label>Email Address</label>
        <input type="text" name="email">
        <div class="error" id="emailErr"></div>
    </div>
    
    <div class="row">
        <input type="submit" value="Submit">
    </div>
</form>
</body>
</html>

Output

In this way, we learned how to validate email in javascript.

How to set word limit in input or Texty using JavaScript.

In this, we set word limit in input by using the char count method in the javascript.

Steps

  • Enter some characters in the box
  • Check limit

Program to set word limit in input or text using javascript

<!doctype html>
<html>
<title>Word limit </title>
<body>
    <h3>
        Enter some characters in the box. (Max. 20 chars limit)
    </h3>
    
    <div>
        <textarea id="tArea" cols="50" 
            oninput="limitChar(this)" maxlength="20"></textarea>

        <p id="charCounter">20 Characters limit</p>
    </div>
</body>

<script>
    let limitChar = (element) => {
        const maxChar = 20;
        
        let ele = document.getElementById(element.id);
        let charLen = ele.value.length;
        
        let p = document.getElementById('charCounter');
        p.innerHTML = maxChar - charLen + ' characters remaining';
        
        if (charLen > maxChar) 
        {
            ele.value = ele.value.substring(0, maxChar);
            p.innerHTML = 0 + ' characters remaining'; 
        }
    }

</script>
</html>

Output

In this way, we learn how to set word limits using JS.

Validate login form using JavaScript

In this, we create a login form using Javascript.

Steps

  • Create from
  • Use field Name and password
  • Set conditions
  • Display output

Program to validate login form using JS

<html>
<body>
  <title>Login form</title>
<script>  
function validateform(){  
var name=document.myform.name.value;  
var password=document.myform.password.value;  
  
if (name==null || name==""){  
  alert("Name can't be blank");  
  return false;  
}else if(password.length<6){  
  alert("Password must be at least 6 characters long.");  
  return false;  
  }  
}  
</script> 
<style>
  form {
    width: 300px;
    background: #fff;
    padding: 15px 40px 40px;
    border: 1px solid #ccc;
    margin: 50px auto 0;
    border-radius: 5px;
}
</style> 
<body>  
<form name="myform" method="post" onsubmit="return validateform()" >  
Name: <input type="text" name="name"><br/>  
Password: <input type="password" name="password"><br/>  
<input type="submit" value="register">  
</form>  
</body>
</html>

Output

In this way, we learned how to validate the login forms using JS.

Validate registration form using JavaScript

In this, we learn to validate the registration form using javascript.

Steps

  • Create a registration form.
  • Take input from the user
  • Validate input
  • Display output

Program to validate registration form in JS

<!DOCTYPE html>
<html>
<head>
<title>Form validation JS</title>
<script>
// Defining a function to display error 
function printError(elemId, hintMsg) {
    document.getElementById(elemId).innerHTML = hintMsg;
}

// Defining a function to validate form 
function validateForm() {
    // Retrieving the values of form elements 
    var name = document.contactForm.name.value;
    var email = document.contactForm.email.value;
    var mobile = document.contactForm.mobile.value;
    var country = document.contactForm.country.value;
    var gender = document.contactForm.gender.value;
    
  // Defining error variables with a default value
    var nameErr = emailErr = mobileErr = countryErr = genderErr = true;
    
    // Validate name
    if(name == "") {
        printError("nameErr", "Please enter your name");
    } else {
        var regex = /^[a-zA-Z\s]+$/;                
        if(regex.test(name) === false) {
            printError("nameErr", "Please enter a valid name");
        } else {
            printError("nameErr", "");
            nameErr = false;
        }
    }
    
    // Validate email address
    if(email == "") {
        printError("emailErr", "Please enter your email address");
    } else {
        // Regular expression for basic email validation
        var regex = /^\S+@\S+\.\S+$/;
        if(regex.test(email) === false) {
            printError("emailErr", "Please enter a valid email address");
        } else{
            printError("emailErr", "");
            emailErr = false;
        }
    }
    
    // Validate mobile number
    if(mobile == "") {
        printError("mobileErr", "Please enter your mobile number");
    } else {
        var regex = /^[1-9]\d{9}$/;
        if(regex.test(mobile) === false) {
            printError("mobileErr", "Please enter a valid 10 digit mobile number");
        } else{
            printError("mobileErr", "");
            mobileErr = false;
        }
    }
    
    // Validate country
    if(country == "Select") {
        printError("countryErr", "Please select your country");
    } else {
        printError("countryErr", "");
        countryErr = false;
    }
    
    // Validate gender
    if(gender == "") {
        printError("genderErr", "Please select your gender");
    } else {
        printError("genderErr", "");
        genderErr = false;
    }
    
    // Prevent the form from being submitted if there are any errors
    if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {
       return false;
    } else {
        // Creating a string from input data for preview
        var dataPreview = "You've entered the following details: \n" +
                          "Full Name: " + name + "\n" +
                          "Email Address: " + email + "\n" +
                          "Mobile Number: " + mobile + "\n" +
                          "Country: " + country + "\n" +
                          "Gender: " + gender + "\n";
    
        // Display input data in a dialog box before submitting the form
        alert(dataPreview);
    }
};
</script>
<style>
    body {
    font-size: 16px;
    background: #f9f9f9;
    font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
}

form {
    width: 300px;
    background: #fff;
    padding: 15px 40px 40px;
    border: 1px solid #ccc;
    margin: 50px auto 0;
    border-radius: 5px;
}
label {
    display: block;
    margin-bottom: 5px
}
label i {
    color: #999;
    font-size: 80%;
}
input, select {
    border: 1px solid #ccc;
    padding: 10px;
    display: block;
    width: 100%;
    box-sizing: border-box;
    border-radius: 2px;
}
.row {
    padding-bottom: 10px;
}
.form-inline {
    border: 1px solid #ccc;
    padding: 8px 10px 4px;
    border-radius: 2px;
}
.form-inline label, .form-inline input {
    display: inline-block;
    width: auto;
    padding-right: 15px;
}
.error {
    color: red;
    font-size: 90%;
}
input[type="submit"] {
    font-size: 110%;
    font-weight: 100;
    background: #006dcc;
    border-color: #016BC1;
    box-shadow: 0 3px 0 #0165b6;
    color: #fff;
    margin-top: 10px;
    cursor: pointer;
}
input[type="submit"]:hover {
    background: #0165b6;
</style>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()"  method="post">
    <h2>Application Form</h2>
    <div class="row">
        <label>Full Name</label>
        <input type="text" name="name">
        <div class="error" id="nameErr"></div>
    </div>
    <div class="row">
        <label>Email Address</label>
        <input type="text" name="email">
        <div class="error" id="emailErr"></div>
    </div>
    <div class="row">
        <label>Mobile Number</label>
        <input type="text" name="mobile" maxlength="10">
        <div class="error" id="mobileErr"></div>
    </div>
    <div class="row">
        <label>Country</label>
        <select name="country">
            <option>Select</option>
            <option>India</option>
            <option>United States</option>
            <option>Australlia</option>
        </select>
        <div class="error" id="countryErr"></div>
    </div>
    <div class="row">
        <label>Gender</label>
        <div class="form-inline">
            <label><input type="radio" name="gender" value="male"> Male</label>
            <label><input type="radio" name="gender" value="female"> Female</label>
        </div>
        <div class="error" id="genderErr"></div>
    </div>
    <div class="row">
        <input type="submit" value="Submit">
    </div>
</form>
</body>
</html>

Output

In this way, we learned how to validate the registration form in JS.