In the previous post you have read about basic javascript validations. Here I am posting some complex javascript validations like validation to restrict user to enter “only characters”, “only number”, “char and num both” and email validation.
Here demo contains some basic fields for validation.
<form method="post" name="myform" onsubmit="return validate()"> First Name: <input type="text" name="fname" id="fname"> Phone: <input type="text" name="phone" id="phone"> Address: <input type="text" name="address" id="address"> Email: <input type="text" name="email" id="email"> Male: <input type="radio" name="rad" id="rad" value="Male">Male Female: <input type="radio" name="rad" id="rad" value="Female">Female <input type="submit" name="submit" value="submit"> </form>
You need to just call validate function on onsubmit on the form. In this validation code, I used “match” function that checks input string with the regular expressions like [a-zA-Z], [0-9a-zA-Z], [0-9].
<SCRIPT language="JavaScript" type="text/javascript">
function validate()
{
flag=true;
error="";
var alphaExp = /^[a-zA-Z]+$/;
var alphaExp1 = /^[0-9a-zA-Z]+$/;
var numExp = /^[0-9]+$/;
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if (!document.myform.fname.value.match(alphaExp))
{
flag=false;
error+="Please enter only characters in First Name \n";
document.myform.fname.focus();
}
else if (!document.myform.phone.value.match(numExp))
{
flag=false;
error+="Please enter only numbers in phone \n";
document.myform.phone.focus();
}
else if (!document.myform.address.value.match(alphaExp1))
{
flag=false;
error+="Please enter num and char only in address \n";
document.myform.address.focus();
}
else if (!document.myform.email.value.match(emailExp))
{
flag=false;
error+="Please enter valid email id \n";
document.myform.email.focus();
}
else if (document.myform.rad[0].checked==false && document.myform.rad[1].checked==false)
{
flag=false;
error+="Please check at leat one radio \n";
document.myform.rad[0].focus();
}
if(flag==false)
{
alert(error);
return flag;
}
}
</script>
This validation script contains smart ways to deal with some complex validations. You can see input string directly checks with regular expressions that yields desired results quickly.
With this code email validation is now easy to perform and implementation.
Enjoy it

May 28th, 2010 at 11:31 am
Hello
Nice script buddy its very useful for perform validation on any type of forms elements…
I was looking for similar validation script.
Thanks
May 28th, 2010 at 11:32 am
Thanks bro…
keep visiting
May 28th, 2010 at 9:26 pm
If you feel any kind of problem regarding implementation, just contact to me. I will try to post reply asap.
August 4th, 2011 at 12:17 pm
Hi this is one of the good jquery plugin for email validation .. i need to validate an email address like this abc@gmail.com.li.li
there must be an alert after entering more domains .