this tutorial will be show how to ajax form validation client side validation in your form using JavaScript. when user typing in the field form will auto check validation without call server side.
for make form validation you need two file php for validation data and javascript, let's go to step 1.
include validate.js
now you can crate formvalidation.php this script will be validation data from your form and will give respone if valid or not.
-
$validationtype = $_GET["validationtype"];
-
$continueSubmit = true ;
-
-
switch ($validationtype)
-
{
-
case ‘ajax’:
-
ProcessAjax(); //if validationtype is ajax go to processajax function
-
break;
-
case ‘php’:
-
processPHP();//if it is php call processphp runction
-
break;
-
}
-
-
function ProcessAjax()
-
{
-
$required = $_GET["sRequired"];
-
$typecheck = $_GET["sTypeCheck"];
-
$val = $_GET["val"];
-
-
-
validateRequired($required,$val,$typecheck);
-
-
-
switch ($typecheck)
-
{
-
case ‘date’:
-
validateDate($val);
-
break;
-
case ‘email’:
-
validateEmail($val);
-
break;
-
}
-
}
-
-
-
function processPHP()
-
{
-
//request the forms variables
-
$user = $_POST["user"];
-
$email= $_POST["email"];
-
global $continueSubmit;
-
-
echo "Username: ";
-
validateRequired("required", $user, "none");//validate user
-
echo "<br />";
-
-
echo "Email: ";
-
validateEmail($email) ;//validate email
-
-
-
if ($continueSubmit)
-
{
-
//submit your form
-
}
-
-
}
-
-
-
function validateRequired($required,$val,$typecheck)
-
{
-
-
-
if ($required == "required")
-
{
-
if ($val == "")
-
{
-
-
echo "Required";
-
exit();
-
}
-
-
if ($val !== "" && $typecheck == "none")
-
{
-
-
echo "Tidak Keren";
-
}
-
}
-
-
}
-
-
-
function validateEmail($val)
-
{
-
global $continueSubmit ;
-
-
if (ereg ("^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$", $val, $regs))
-
{
-
echo "Thank You";
-
}
-
else
-
{
-
$continueSubmit = false;
-
echo "Invalid Email Address";
-
}
-
}
next you create html form give name index.html
-
<form name="form1" id="form1" method="post" action="formvalidation.php?validationtype=php" onSubmit="return validate();">
-
-
<table width="500">
-
-
<tr>
-
-
<td width="130">Username </td>
-
-
<td width="170"><input type="text" name="user"
-
tabindex="1" id="user" class="validate required none
-
usermsg"/></td>
-
-
<td id ="usermsg" class="rules">Required</td>
-
-
</tr>
-
-
-
-
<tr>
-
-
<td>Email </td>
-
-
<td><input type="text" name="email" tabindex="2"
-
id="email" class="validate required email emailmsg" /></td>
-
-
<td id="emailmsg" class="rules">Required</td>
-
-
</tr>
-
-
-
-
<tr>
-
-
<td><input type="submit" name="Submit" value="Submit" tabindex="5" /></td>
-
-
</tr>
-
-
-
-
</table>
-
-
-
-
</form>
-
-
</fieldset>
you just need two file to run ajax form validation for see demo and download file you can click here :
Demo Form Validation | Download Form Validation
Share on Facebook
Posted by admin @ 12 October 2009
11:54 pm
Hello from Russia!
Can I quote a post in your blog with the link to you?