Form Validation In JavaScript With Example

Performing validation using JavaScript is an easy task.

Form validation is required to prevent web form abuse by malicious users. Improper validation of form data is one of the main causes of security vulnerabilities. It exposes your website to attacks such as header injections, cross-site scripting, and SQL injections.

  • header injection attacks can be used to send email spam from your web server
  • cross-site scripting may allow an attacker to post any data to your site
  • SQL injection may corrupt your database back-end.


Now let’s see a simple example, how to perform FORM VALIDATION IN JAVASCRIPT. The following code must be written in HTML document.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Validation</title>
    <script type="text/javascript">
    function fun1()
    {
        var a=document.getElementById("nm").value;
        var b=document.getElementById("em").value;
        var c=document.getElementById("pass").value;
        var d=document.getElementById("cpass").value;
        var e=document.getElementById("ag").value;
        
        /*-----REGULAR EXPRESSION TO VALIDATE EMAIL-----*/
        var pat=/^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{3,4}$/; 
        
        if(a=="" || a==null)
        {
            alert("Plase Enter Your Name");
            return false;
        }
        if(!pat.test(b))
        {
            alert("Enter Valid Email ID")
            return false;
        }
        if(c=="" || c==null)
        {   
            alert("Enter Password");
            return false;
        }
        if(d!=c)
        {
            alert("Password missmatch");
            return false;
        }
        if(e<18)
        {
            alert("Not eligible to register");
            return false;
        }
    }
    </script>
    
</head>
<body>
<form action="xyz.html" method="get">
<table>
<tr>
<th>Name:</th>
<td><input type="text" id="nm" name="nm" /></td>
</tr>
<tr>
<th>Email:</th>
<td><input type="text" id="em" name="em" /></td>
</tr>
<tr>
<th>Password</th>
<td><input type="password" id="pass" name="pass" /></td>
</tr>
<tr>
<th>Confirm Password:</th>
<td><input type="password" id="cpass" name="cpass" /></td>
</tr>
<tr>
<th>Age:</th>
<td><input type="text" id="ag" name="ag" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit"
 id="btn" name="nm" onclick="return fun1()" /></td>
</tr>
</table>
</form>
</body>
</html>

Download Demo Work Here


JavaScript, ASP.Net & PHP Web Developer. Connect with me on Facebook and Twitter.

Share This Post

Related Articles

Powered by Paras Babbar · Designed by Paras Babbar