L8 Form Validation
L8 Form Validation
It is important to validate the form submitted by the user because it can have inappropriate values.
So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing will be faster than
server-side validation. Most of the web developers prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.
<html>
<head>
<title>one</title>
<script>
function validateform()
{
var me=document.WAINAINA.me.value;
if (me==null || me=="")
{
alert("Name can't be blank");
return false;
}
}
</script>
</head>
<body bgcolor="lightgreen">
<form name="WAINAINA" onsubmit="return validateform()" >
Name: <input type="text" name="me"><span style="color:#ff0000">*</span><br/>
<input type="submit" value="register">
</form>
</body>
</html>
OUTPUT:
<html>
<head>
<title>one</title>
<script>
function validateform()
{
var password=document.WAINAINA.password.value;
if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
</head>
<body bgcolor="lightgreen">
<form name="WAINAINA" onsubmit="return validateform()" >
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
OUTPUT
OUTPUT:
Example Five: A JavaScript program to validate the password entered is the same.
<html>
<head>
<title>one</title>
<script type="text/javascript">
function matchpass()
{
var firstpassword=document.WAINAINA.password.value;
var secondpassword=document.WAINAINA.password2.value;
if(firstpassword==secondpassword)
{
return true;
}
else
{
alert("password must be same!");
return false;
}
}
</script>
</head>
OUTPUT:
There are many criteria that need to be follow to validate the email id such as:
<html>
<head>
<title>one</title>
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@"); //method returns the first index at which a given element can be
found in the array, or -1 if it is not present.
var dotposition=x.lastIndexOf("."); //returns the index (position) of the last occurrence of a
specified value in a string.
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
OUTPUT: