National Institute of Electronics & Inf ormation Technology
Gorakhpur
chapter 06: JavaScript contd.
Topics to be covered
Form Validations
JS Events.
Form Validations
JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and other
fields.
<html>
<body>
<script type="text/javascript">
function data(){
var a=document.getElementById("n1").value;
var b=document.getElementById("n2").value;
var c=document.getElementById("n3").value;
var d=document.getElementById("n4").value;
if(a==""||b==""||c==""||d=="")
alert("all fields are mendatory");
return false;
}
National Institute of Electronics & Inf ormation Technology
Gorakhpur
else if(b.length<10||b.length>10){
alert("number should be of 10 digits!please enter valid number");
return false;
else if(isNaN(b))
alert("only numbers are allowed !please enter valid number");
return false;
else if(c.length<6)
alert("password must be 6 character long!");
return false;
else if(c!=d)
alert("please enter same password");
return false;
else {
true; }
</script>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
<form onsubmit="return data()" action="submit.html"><br><br>
name: <input type="text" id="n1"><br><br>
contact: <input type="text" id="n2"><br><br>
password: <input type="password" id="n3"><br><br>
confirm password: <input type="password" id="n4"><br><br><br>
<input type="submit" value="submit" id="">
</form>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Email validation:
There are many criteria that need to be follow to validate the email id such as:
email id must contain the @ and . character
There must be at least one character before and after the @.
There must be at least two characters after . (dot).
<html><body>
<script type="text/javascript">
function data(){
var e=document.getElementById("n5").value;
if(e.indexOf('@')<=0)
alert("invalid email id !please correct '@' place");
return false;
else if((e.charAt(e.length-4)!='.') && (e.charAt(e.length-3)!='.'))
alert("invalid email id! please correct '.' place");
return false;
} else{ true;
}}
</script>
<form onsubmit="return data()" action="submit.html"><br><br>
<h1> Email validation </h1>
email:<input type="text" id="n5"><br><br>
<input type="submit" value="submit" id="">
</form></body>
</html>