As sir mentioned about using regular expression for doing this, i managed to find one good way of doing it. Just wanted to share it with everyone. Here's the code
<html>
<head>
<script type="text/javascript">
var RE_EMAIL = /^(\w+[\-\.])*\w+@(\w+\.)+[A-Za-z]+$/;
function validate(form){
var email=form.email.value;
if (!RE_EMAIL.test(email)){
alert("You have to enter a valid email")
return false;
}
else
return true;
}
</script>
</head>
<body>
<form onsubmit="return validate(this);">
Email: <input type="text" name="email" size="25"><br/>
<input type="submit" value="Submit">
<input type="reset" value="Reset Form">
</form>
</body>
</html>
To understand the regular expression let me break it into parts.Say my email address is firstname.lastname@mydomain.com
/^(\w+[\-\.])*: This will match firstname.
\w+@: This will match lastname@
(\w+\.)+[A-Za-z]+$/: This will match yourdomain.com
please read http://www.learn-javascript-tutorial.com/RegularExpressions.cfm if you want dig more into it.
Cheers
Sep 27, 2009