Home >>Javascript Tutorial >JavaScript form validation

JavaScript form validation

Javascript Form Validation

JavaScript form validation using HTML is very important to validate the form submitted by the user because it may some have inappropriate values. Hence, the validation is must authenticate the user.

JavaScript delivers us the facility to validate the form on the client-side in order to make the data processing faster than server-side validation. Majority of the web developers prefer html form validation using JavaScript.

Through JavaScript, you can validate name, password, email, date, mobile numbers and more fields.
Let's understand the JavaScript Form Validation with an Example:

Here is the example, we are going to validate the name and password. Please note that the name can’t be empty and password can’t be less than 6 characters long.

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

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>registration form with javascript validation</title>
<script type="text/javascript">
function chk()
{
var n= document.f1.fn.value;
var l=document.f1.ln.value;
var e=document.f1.eid.value;
if(n=="")
{
alert("fill your first name");
document.f1.fn.focus();
return false;
}
else if(l=="")
{
alert("fill your last name");
document.f1.ln.focus();
return false;
}
else if(e=="")
{
alert("fill your email");
document.f1.eid.focus();
return false;
}
return true

}
</script>


</head>

<body>
<form method="" action="" name="f1">
<table width="430" border="0">
<tr>
<td width="115" height="36" scope="col">Your first name </td>
<td width="144" scope="col"><input name="fn" type="text" id="fn"/></td>
<td width="149" scope="col" style="color:red" id="err"></td>
</tr>
<tr>
<td>Your last name</td>
<td><input type="text" name="ln" id="ln"/></td>
<td style="color:red" id="err1"></td>
</tr>
<tr>
<td>your email</td>
<td><input type="text" name="eid" id="eid"/></td>
<td style="color:red" id="err2"></td>
</tr>

<tr>
<td colspan="3">
<input type="submit" onclick="return chk()" value="Save Data"/>
</td>
</tr>
</table>
</form>
</body>
</html>

Popular Tutorials