Jan 23, 2010

"Email, Name, Age Validation in Javascript"

How to do email, name and age validation in JavaScript?

In this below example we validating three fields such as Name,Age and Email. First checking whether the given email id has symbols "@" and "." (dot).
Because all emails will have . and @ to represent domain and user belongs to. For example "example@gmail.com" . So we an email id will have both "@" and "." symbol.
We can assume that an email id without "@" and "." is invalid. It would better if we check charlength before @ symbol also.

Obviously Age shoul be a number and between 1 to 100. This is how we validating age should not be greater than 100.

Same way validating first name also. In my example i just validating that firstname must be less than 10 charecters. We can do it as we need.

File :  EmailValidate_JS.html

<html>
<head>
<script type="text/javascript">
function validate(){
var at=document.getElementById("email").value.indexOf("@");
var dot=document.getElementById("email").value.indexOf(".");
var age=document.getElementById("age").value;
var fname=document.getElementById("fname").value;
submitOK="true";
if (fname.length>10)
 {
alert("The name must be less than 10 characters");
 submitOK="false";
}
if (isNaN(age)||age<1||age>100)
 {
alert("The age must be a number between 1 and 100");
 submitOK="false";
}
if (at==-1)
 {
alert("Not a valid e-mail!");
 submitOK="false";
}
if (dot==-1)
 {
alert("Not a valid e-mail!");
 submitOK="false";
}
if (submitOK=="false") {
 return false;
 }
}
</script>
</head>
<body>
<form action="validationresult.html" onsubmit="return validate()">
Name (max 10 chararcters): <input type="text" id="fname" size="20"><br />
Age (from 1 to 100): <input type="text" id="age" size="20"><br />
E-mail: <input type="text" id="email" size="20"><br />
<br /><input type="submit" value="Submit">
</form>
</body>
</html>                   


======================
Publicize yourself ... Free!
http://saalram.com
======================


8 comments:

  1. age validation worked thanks a lot

    ReplyDelete
  2. Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts. www.verifications.io

    ReplyDelete

Saalram.com

Saalram
Publicize yourself ...
http://saalram.com

Free !!!


Place your Ad here - Free!!!
just drop us a mail ... saalram.service@gmail.com

Free !!!