How To Validate Form In Javascript?

It is important to validate the form submitted by the user because it can have blank values. So, validation is a must to authenticate users.

JavaScript library provides a facility to validate the form on the client-side so data processing will be faster other than server-side validation. Most of the any developers prefer JavaScript form validation.

so, JavaScript we can validate name, password, email, date, mobile numbers, and more fields.

JavaScript Form Validation Example

In this example, we are going to validate the name and address. The name can’t be empty and address can’t be empty.

Here, we are validating on form submit. user will be not forwarded to the next page until given values are correct.

Stap 1

Next step, we have to create "index.php". put bellow code in this file:

Create: /index.php

function validateform(){  
var user_name=document.myform.user_name.value;  
var user_address=document.myform.user_address.value;  
if (user_name==null || user_name==""){  
  alert("User Name can't be blank");  
  return false;  
if (user_address==null || user_address==""){  
  alert("User Address can't be blank");  
  return false;  
Stap 2

In this step. put bellow code in this file:


      <title>how to validate form in javascript?</title>
    <form method = "post" name="myform" onsubmit="return validateform()" >
        <table width = "400" border = "0" cellspacing = "1" cellpadding = "2">
            <td width = "100">User Name</td>
            <td><input name = "user_name" type = "text" placeholder="User Name"></td>
            <td width = "100">User Address</td>
            <td><input name = "user_address" type = "text" placeholder="User Address"></td>
            <td width = "100"> </td>
            <td> </td>
            <td width = "100"> </td>
                <input name = "submit" type = "submit" value = "Add User">


I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!