Sunday, 7 June 2015

PHP Form Validation

It is very essential to have the input to your form validated before taking the form submission data for further processing. When there are many fields in the form, the PHP validation script becomes too complex. Moreover, since you are doing the same or similar validation for most of the forms that you make, just too much of duplicate effort is spent on form validations. Here I am going to validate form using JavaScript code .
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.
w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function fun()
{
if(document.f.name.value=='')
{
alert("please enter name");
document.f.name.focus();
return false;
}
else if(!document.f.gender[0].checked && !document.f.gender[1].checked)
{
alert("please choose gender");
return false;
}
else if(!document.f.qual[0].checked && !document.f.qual[1].checked && !document.f.qual[2].checked )
{
alert("please choose qualification");
return false;
}
else if(document.f.city.value=='Select')
{
alert("Please select city");
return false;
}

else if(document.f.address.value=='')
{
alert("please enter address");
document.f.address.focus();
return false;
}

else
{
return true;
}
}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<table border="1">
<tr><td colspan="2" align="center"><font size="+2">Registration Form</font></td></tr>
<form method="post" name="f" onsubmit="return fun()">
<tr><td>name</td><td><input type="text" name="name"></td>
<tr><td>Gender</td><td>Male<input type="radio" name="gender" value="Male">
Female<input type="radio" name="gender" value="Female">
</td></tr>
<tr><td>Qualification</td><td>BCA<input type="checkbox" name="qual" value="BCA">
MCA<input type="checkbox" name="qual" value="MCA">
Other<input type="checkbox" name="qual" value="Other"></td>
</tr>
<tr><td>City</td>
<td><select name="city">
<option>Select</option>
<option>Delhi</option>
<option>Noida</option>
<option>Gorakhpur</option>
</select>
</td></tr>

<tr><td>Address<td><textarea name="address"></textarea></td></tr>

<tr><td align="center" colspan="2"><input type="submit" name="Submit" value="Submit"></td></tr>
</form>
</table>
</body>
</html> 
http://tutorialspinpoint.com/php/php_validation.html

Note-
You can directly write JavaScript code in head section of html page or you can create external page
 for js code and call that page in head section.
 And JavaScript code must be inside <script>(opening) and  </script>(closing) tag 

Eg.  If you  save file named val.js then  calling as fallow:

<head>
<script src=”val.js”>  
</script>
</head>

Or
<head>
<script src=”js file path”>  
</script>
</head>

Sunday, 31 May 2015