Sunday, June 20, 2010

Simple HTML Form Validation

This form made with simple and easily understanding. So this will help you to create a better form validation using javascript. I've written below code with my knowledge level. If anyone having good idea or suggestion please let me know ...


HTML Code



<form name="sample" method="post" action="#" onsubmit="return validatethis()">
<p><input type="text" value="Enter your name" name="name" onfocus="clearthis(this)" onblur="rollback(this)"></p>
<p><input type="text" value="Enter your Ph no." name="phone" onfocus="clearthis(this)" onblur="rollback(this)"></p>
<p><input type="text" value="Enter your Email" name="email" onfocus="clearthis(this)" onblur="rollback(this)"></p>
<p><input type="radio" id="male" value="Male" name="gender">Male</p>
<p><input type="radio" id="female" value="Female" name="gender">Female</p>
<p><input type="checkbox" value="read" name="option">Read</p>
<p><input type="checkbox" value="write" name="option">Write</p>
<p><select name="age">
<option value="" selected>Select your age</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
</select></p>
<p><input type="submit" value="Submit">
<input type="reset" value="Reset">
</p>
</form>


Javascript Code



function clearthis(val)
{
if (val.defaultValue==val.value) val.value = "";
}
function rollback(val)
{
var valcon = val.defaultValue;
if (val.value == 0) {
val.value = valcon;
val.style.backgroundColor ="#ff0";
}
}
function validatethis()
{
var stripped = document.sample.phone.value.replace(/[\(\)\.\-\ ]/g, '');
var em = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

var a = document.sample.name.value;
var b = document.sample.phone.value;
var c = document.sample.email.value;
var h = document.sample.age;

if (a == "Enter your name" || a == 0){
alert("Enter your Name");
a.focus();
return false;
}

if (b == "Enter your Ph no." || b == 0){
alert("Enter your ph no.");
b.focus();
return false;
}
else if (isNaN(parseInt(stripped))) {
alert("The phone number contains illegal characters.\n");
}
if (c == "Enter your Email" || c == 0){
alert("Enter your Email");
c.focus();
return false;
}
else if (em.test(c)==false) {
alert("The Email contains illegal characters.\n");
return false;
}

if (!document.sample.gender[0].checked && !document.sample.gender[1].checked)
{
alert("Select Gender");
return false;
}

if (!document.sample.option[0].checked && !document.sample.option[1].checked)
{
alert("Select any Option");
return false;
}
if (h.selectedIndex > 0)
{
}
else {
alert("Select your age");
return false;
}
}



Very thanks !!! Catch you later soon

No comments: