Validation is used to
validate the form submitted by the user.
JavaScript provides client
side validation.
client side validation is faster
than server-side validation.
Through JavaScript, we can validate name,
password, email, date, mobile number fields etc.
Example: Registration form validation
<!doctype
html>
<html
lang="en:US">
<head>
<title>Create
an Account</title>
<meta
charset="UTF-8">
</head>
<style>
body{background-image:url("Blank-Background-for-Desktop.jpg")}
#loginbtn{background-color:green;}
#resetbtn{background-color:Red;}
caption{font-size:20px;}
</style>
<script
type="text/javascript">
function
validateform(){
var
fname=document.myform.firstname.value;
var
lname=document.myform.lastname.value;
var
emailID=document.myform.email.value;
var
atposition=emailID.indexOf("@");
var
dotposition=emailID.lastIndexOf(".");
var
password1=document.myform.password.value;
var
password2=document.myform.password3.value;
//fname validation(required field
validation )
if(fname==null
|| fname==""){
document.getElementById("mona").innerHTML=" First Name can't be blank";
return
false;
}
//lname validation(required field
validation )
else
if(lname==null || lname=="")
{
document.getElementById("mona1").innerHTML=" Last Name can't be blank";
return false;
}
//email validation
else
if(atposition<1 || dotposition<atposition+2 ||
dotposition+2>=emailID.length)
{
document.getElementById("mona2").innerHTML=" Please enter a valid e-mail
address";
return false;
}
// password validation
else
if(password1.length<6)
{
document.getElementById("mona3").innerHTML=" Password must be at least 6 characters
long.";
return false;
}
//confirm password validation
if(password1==password2){
return true;
}
else{
document.getElementById("mona4").innerHTML=" password must be same...!!!";
return false;
}
}
</script>
<body>
<form
name="myform" method="post" action="#"
onsubmit="return validateform()" >
<table>
<h1><b>Create
an account</b></h1>
<tr>
<td>First
Name</td>
<td>:
</td>
<td><input
type="text" name="firstname"><span
id="mona"></span></td>
</tr><br>
<tr>
<td>Last
Name</td>
<td>:
</td>
<td><input
type="text" name="lastname"><span
id="mona1"></span></td>
</tr>
<tr>
<td>Email
ID</td>
<td>:
</td>
<td><input
type="text" name="email"><span
id="mona2"></span></td>
</tr>
<tr>
<td>Age</td>
<td>:
</td>
<td><input
type ="number" name="Age"><span
id="mona5"></span></td>
</tr><br>
<tr>
<td>Create
a new Password</td>
<td>:
</td>
<td><input
type="password" name="password"><span
id="mona3"></span></td>
</tr>
<tr>
<td>Re-enter
Password</td>
<td>:
</td>
<td><input
type="password" name="password3"><span
id="mona4"></span></td>
</tr>
<br>
</table>
<button
type="submit" name="Submit" id
="loginbtn"><b>Login</b></button>
<button
type="button" name="Submit"
id="resetbtn"><b>Reset</b></button><br><br></b>
Already
Registered!!!     <a
href="#">Register Here!!!</a>
</form>
</body>
</html>
Output:
No comments:
Post a Comment