Today I am going to describe how to to validate an html form using javascript. If you are using jquery and modern browser then this can be very easy but what if you need support for old browser and you want use pure javacript.
Assignment
Write an html page with form that validates name,registration number,address,department and result information of a student. form will validate following REGISTERATION ID =1234 , NAME = "NAVIN" , ADDRESS = "KOLKATA-008" , DEPARTMENT ="CMAV" AND RESULT =80 (INTEGER) for valid registration.
Are you ready , lets dive into coding
<html>
<head>
<title>STUDENT REGISTRATION</title>
</head>
<body>
<h2>Write an html page with form that validates name,registration number,address,department and result information of a student</h2>
<script type="text/javascript">
function validate(){
var a=document.forms["myForm"]["t1"].value;
var b=document.forms["myForm"]["t2"].value;
var c=document.forms["myForm"]["t3"].value;
var d=document.forms["myForm"]["t4"].value;
var e=document.forms["myForm"]["t5"].value;
if(a==null||a==""){
alert("Reg No. can't be empty");
return false;
}
else if(b==null||b==""){
alert("Name can't be empty");
return false;
}
else if(c==null||c==""){
alert("Address can't be empty");
return false;
}
else if(d==null||d==""){
alert("department can't be empty ");
return false;
}
else if(e==null||e=="" || checkInt(e) == true){
alert("Enter a valid integer (Result)");
return false;
}
else if(a=="1234" && b=="NAVIN" && c=="KOLKATA-008" && d=="CMAV" && e=="80"){
alert("Succsessfully registerd");
return false;
}
else{
alert("Invailid Registration");
return false;
}
}
function checkInt(data){
if (data !== parseInt(data, 10))
return data;
}
</script>
<form name="myForm" action="" onsubmit="return validate()" method="post">
<table align="center" border="1" color="red">
<tr>
<td>REGISTERATION ID:<input type="text" name="t1" ></td>
<tr><td>NAME:<input type="text" name="t2"></td></tr>
<tr><td>ADDRESS:<input type="text" name="t3"></td></tr>
<tr><td>DEPARTMENT:<input type="text" name="t4"></td></tr>
<tr><td>RESULT (%):<input type="text" name="t5"></td></tr>
<br/><br/><br/>
<tr><td><input type="submit" value="Submit"></td></tr>
</form>
</body>
</html>