Full-service Internet Marketing & Web Development
Recent Posts

Sponsors
![]() |
jQuery for Real time Server-side Form ValidationDawn Rossi, 07-17-2009 |
jQuery is a JavaScript Library that includes document traversing, drag&drop, date picker, tabs animating, and Ajax interactions for rapid web development. It's widely deployed and used by Google, Digg, Mozilla as well as many other huge sites.
As part of this post, I'll demonstrate how to use jQuery for real time server-side form validation.
The Challenge
Most HTML forms use simple Javascript to validate user input, before the form is submitted to the server.
A javascript function runs inside the browser and validates that a date field is valid, a username field doesn't contain invalid characters etc.
Providing user input passes these simple client-side validation tests, the form is submitted to the server, where the server performs additional validations on the entered data.
Some examples where this approach is lacking:
* A username may be valid on the client side, but already taken by the time the form is submitted.
* Information on the server-end is required to validate a password
* USPS lookup is necessary to validate an address / zip code etc.
jQuery
Since data on the server side is required for some validations, we need a way to ping the server and validate fields as the user is typing text in the form.
jQuery to the rescue!
Start by including jQuery in your html code:
<script type="text/javascript" src="https://softwareprojects.com/script/jquery.js"></script>
Designating a field as required is easy - simply add a hidden input tag with the name of require_FIELDNAME:
Enter your name: <input name=fullname type=text>
<input type=hidden name=require_fullname>
Integrating server-side validation with a form field and displaying an error message if validation fails, can be done with a single call:

$(document).ready(function () {
$('#username').bind('blur',function(e){
$.get("/validate_username.php", {login: $(this).val()}, function(data){
$('#username_message').html(data);
}, 'html');
});
});
Complete Example
This example features server-side validation of a password and username (check for invalid characters and verify username is available), displaying an inline error message if validation fails.
Here's how the end result looks like:

HTML code:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>jQuery Demo</title>
<link rel="stylesheet" href="style2.css" type="text/css" media="screen" />
<script type="text/javascript" src="https://softwareprojects.com/script/jquery.js"></script>
<script language="javascript">
<!--
$.ajaxSetup ({
cache: false
});
// Validate subdomain using validateusername.php
// Display result into s_dom div tag
$(document).ready(function () {
$('#subdomain').bind('blur',function(e){
$.get("/validateusername.php", {login: $(this).val()}, function(data){
$('#s_dom').html(data);
}, 'html');
});
// Validate password using validatepassword.php
// Display result into s_password div tag
$('#password').bind('blur',function(e){
$.get("/validatepassword.php", {password: $(this).val()}, function(data){
$('#s_password').html(data);
}, 'html');
});
// Validate password2 using validatepassword.php
// Display result into s_password2 div tag
$('#password2').bind('blur',function(e){
$.get("/validatepassword.php", {password: $(this).val()}, function(data){
$('#s_password2').html(data);
}, 'html');
});
});
//-->
</script>
</head>
<body>
<div id="page">
<!--main start-->
<div class="main">
<div class="rbody">
<div >
<div class="roundbodytop">
<div class="innerbody">
<div class="leftside3">
<p align="center"><img src="copy/images/homebusinessprofitblueprint2.png" width="694" height="82" /></p>
<p align="center" class="mainRedTitle"></p>
<p align="center"> <span class="mainRedTitle"><strong>Congratulations
<?=$name?>! Your Account Is Now Active. The Final Step Is To Personalize Your System Information Below.</strong></span>
</p>
<p align="center" class="blacktitle"><strong>Please
choose a password and system subdomain below.*
The subdomain will be part of your personal link to
your system.* </strong></p>
<p>*</p>
<form id="form1" name="form1" method="post" action="thankyou1.php">
<table width="100%" border="0" cellpadding="0">
<tr>
<td width="22%"><div align="right" class="text14"><strong>System Details</strong></div></td>
<td width="78%">*</td>
</tr>
<tr>
<th><span class="red">*</span> Password :</th>
<td><input name="password" type="password" class="InputBoxFront" size="40" maxlength="100" id="password" />
<span class="red" id="s_password"><? if (isset($_POST['save'])) {
if ($_POST['password']== '') {
echo "This field must be filled in";
$all_ok=false;
}
} ?></span> </td>
</tr>
<tr>
<th><span class="red">*</span> Password verification :</th>
<td><input name="password2" type="password" class="InputBoxFront" size="40" maxlength="100" id="password2" /> <span class="red" id="s_password2"></span>
<span class="red"><? if (isset($_POST['save'])) {
if ($_POST['password2']== '') {
echo "This field must be filled in";
$all_ok=false;
} else {
if ($_POST['password2'] != $_POST['password']) {
echo "Passwords must match";
$all_ok=false;
}
}
} ?></span> </td>
</tr>
<tr>
<th><span class="red">*</span> System subdomain choice :</th>
<td><input name="subdomain" type="text" class="InputBoxFront" size="10" maxlength="100" id="subdomain" />
.homebusinessprofitblueprint.com
<span class="red"><? if (isset($_POST['save'])) {
if ($_POST['subdomain']== '') {
echo "This field must be filled in";
$all_ok=false;
}
} ?></span><div id="s_dom" class="red"></div> </td>
</tr>
<tr>
<td colspan="2" align="center">*</td>
</tr>
<tr>
<td colspan="2" align="center"><div align="center">
<a href="javascript:OnUpdate();"><img src="images/homebut3.png" border="0" /></a>
</div></td>
</tr>
</table>
</form>
<p>*</p>
<p>*</p>
</div>
</div>
</div>
</div>
</div>
<SCRIPT>
function OnUpdate()
{
// Basic Javascript validation
if (document.getElementById('form1').password.value=="")
{
alert("Password is required");
return;
}
if (document.getElementById('form1').password2.value=="")
{
alert("Please repeat the password");
return;
}
if (document.getElementById('form1').subdomain.value=="")
{
alert("Subdomain is required");
return;
}
if (document.getElementById('form1').password.value!=
document.getElementById('form1').password2.value)
{
alert("The passwords should be the same");
return;
}
// Server-side validation
// Username
$.get("/validateusername.php", {login: $('#subdomain').val()}, function(data)
{
if (data!="")
{
alert("Invalid subdomain");
return;
}
}, 'html');
// Password
$.get("/validatepassword.php", {password: $('#password').val()}, function(data)
{
if (data!="")
{
alert("Invalid password");
return;
}
}, 'html');;
document.getElementById('form1').submit();
}
</SCRIPT>
The validateusername.php file:
// Connect to your database
mysql_connect("host","username","password");
// Check if we already have a customer with this username
$Result = mysql_query("SELECT * FROM customers where login='".mysql_real_escape_string($login)."' limit 1");
if (!empty($login) && $login != 'www')
{
if (mysql_num_rows($Result)>0)
{
echo "Username already exists";
}
else
if (preg_match("/[^A-Za-z0-9_-]/",$login))
{
echo "Invalid username. Please only use A-Z, a-z and 0-9 characters";
}
}
else
{
echo 'Incorrect username';
}
The validatepassword.php file:
if (preg_match("/[^A-Za-z0-9_-!]/",$password))
{
echo 'Invalid password. Please only use A-Z, a-z, 0-9, "-" or "!"';
}
As part of this post, I'll demonstrate how to use jQuery for real time server-side form validation.
The Challenge
Most HTML forms use simple Javascript to validate user input, before the form is submitted to the server.
A javascript function runs inside the browser and validates that a date field is valid, a username field doesn't contain invalid characters etc.
Providing user input passes these simple client-side validation tests, the form is submitted to the server, where the server performs additional validations on the entered data.
Some examples where this approach is lacking:
* A username may be valid on the client side, but already taken by the time the form is submitted.
* Information on the server-end is required to validate a password
* USPS lookup is necessary to validate an address / zip code etc.
jQuery
Since data on the server side is required for some validations, we need a way to ping the server and validate fields as the user is typing text in the form.
jQuery to the rescue!
Start by including jQuery in your html code:
<script type="text/javascript" src="https://softwareprojects.com/script/jquery.js"></script>
Designating a field as required is easy - simply add a hidden input tag with the name of require_FIELDNAME:
Enter your name: <input name=fullname type=text>
<input type=hidden name=require_fullname>
Integrating server-side validation with a form field and displaying an error message if validation fails, can be done with a single call:

$(document).ready(function () {
$('#username').bind('blur',function(e){
$.get("/validate_username.php", {login: $(this).val()}, function(data){
$('#username_message').html(data);
}, 'html');
});
});
Complete Example
This example features server-side validation of a password and username (check for invalid characters and verify username is available), displaying an inline error message if validation fails.
Here's how the end result looks like:

HTML code:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>jQuery Demo</title>
<link rel="stylesheet" href="style2.css" type="text/css" media="screen" />
<script type="text/javascript" src="https://softwareprojects.com/script/jquery.js"></script>
<script language="javascript">
<!--
$.ajaxSetup ({
cache: false
});
// Validate subdomain using validateusername.php
// Display result into s_dom div tag
$(document).ready(function () {
$('#subdomain').bind('blur',function(e){
$.get("/validateusername.php", {login: $(this).val()}, function(data){
$('#s_dom').html(data);
}, 'html');
});
// Validate password using validatepassword.php
// Display result into s_password div tag
$('#password').bind('blur',function(e){
$.get("/validatepassword.php", {password: $(this).val()}, function(data){
$('#s_password').html(data);
}, 'html');
});
// Validate password2 using validatepassword.php
// Display result into s_password2 div tag
$('#password2').bind('blur',function(e){
$.get("/validatepassword.php", {password: $(this).val()}, function(data){
$('#s_password2').html(data);
}, 'html');
});
});
//-->
</script>
</head>
<body>
<div id="page">
<!--main start-->
<div class="main">
<div class="rbody">
<div >
<div class="roundbodytop">
<div class="innerbody">
<div class="leftside3">
<p align="center"><img src="copy/images/homebusinessprofitblueprint2.png" width="694" height="82" /></p>
<p align="center" class="mainRedTitle"></p>
<p align="center"> <span class="mainRedTitle"><strong>Congratulations
<?=$name?>! Your Account Is Now Active. The Final Step Is To Personalize Your System Information Below.</strong></span>
</p>
<p align="center" class="blacktitle"><strong>Please
choose a password and system subdomain below.*
The subdomain will be part of your personal link to
your system.* </strong></p>
<p>*</p>
<form id="form1" name="form1" method="post" action="thankyou1.php">
<table width="100%" border="0" cellpadding="0">
<tr>
<td width="22%"><div align="right" class="text14"><strong>System Details</strong></div></td>
<td width="78%">*</td>
</tr>
<tr>
<th><span class="red">*</span> Password :</th>
<td><input name="password" type="password" class="InputBoxFront" size="40" maxlength="100" id="password" />
<span class="red" id="s_password"><? if (isset($_POST['save'])) {
if ($_POST['password']== '') {
echo "This field must be filled in";
$all_ok=false;
}
} ?></span> </td>
</tr>
<tr>
<th><span class="red">*</span> Password verification :</th>
<td><input name="password2" type="password" class="InputBoxFront" size="40" maxlength="100" id="password2" /> <span class="red" id="s_password2"></span>
<span class="red"><? if (isset($_POST['save'])) {
if ($_POST['password2']== '') {
echo "This field must be filled in";
$all_ok=false;
} else {
if ($_POST['password2'] != $_POST['password']) {
echo "Passwords must match";
$all_ok=false;
}
}
} ?></span> </td>
</tr>
<tr>
<th><span class="red">*</span> System subdomain choice :</th>
<td><input name="subdomain" type="text" class="InputBoxFront" size="10" maxlength="100" id="subdomain" />
.homebusinessprofitblueprint.com
<span class="red"><? if (isset($_POST['save'])) {
if ($_POST['subdomain']== '') {
echo "This field must be filled in";
$all_ok=false;
}
} ?></span><div id="s_dom" class="red"></div> </td>
</tr>
<tr>
<td colspan="2" align="center">*</td>
</tr>
<tr>
<td colspan="2" align="center"><div align="center">
<a href="javascript:OnUpdate();"><img src="images/homebut3.png" border="0" /></a>
</div></td>
</tr>
</table>
</form>
<p>*</p>
<p>*</p>
</div>
</div>
</div>
</div>
</div>
<SCRIPT>
function OnUpdate()
{
// Basic Javascript validation
if (document.getElementById('form1').password.value=="")
{
alert("Password is required");
return;
}
if (document.getElementById('form1').password2.value=="")
{
alert("Please repeat the password");
return;
}
if (document.getElementById('form1').subdomain.value=="")
{
alert("Subdomain is required");
return;
}
if (document.getElementById('form1').password.value!=
document.getElementById('form1').password2.value)
{
alert("The passwords should be the same");
return;
}
// Server-side validation
// Username
$.get("/validateusername.php", {login: $('#subdomain').val()}, function(data)
{
if (data!="")
{
alert("Invalid subdomain");
return;
}
}, 'html');
// Password
$.get("/validatepassword.php", {password: $('#password').val()}, function(data)
{
if (data!="")
{
alert("Invalid password");
return;
}
}, 'html');;
document.getElementById('form1').submit();
}
</SCRIPT>
The validateusername.php file:
// Connect to your database
mysql_connect("host","username","password");
// Check if we already have a customer with this username
$Result = mysql_query("SELECT * FROM customers where login='".mysql_real_escape_string($login)."' limit 1");
if (!empty($login) && $login != 'www')
{
if (mysql_num_rows($Result)>0)
{
echo "Username already exists";
}
else
if (preg_match("/[^A-Za-z0-9_-]/",$login))
{
echo "Invalid username. Please only use A-Z, a-z and 0-9 characters";
}
}
else
{
echo 'Incorrect username';
}
The validatepassword.php file:
if (preg_match("/[^A-Za-z0-9_-!]/",$password))
{
echo 'Invalid password. Please only use A-Z, a-z, 0-9, "-" or "!"';
}
![]() |
Eugene Bond, 08-05-2009 |
What about validating username format first and then, in case it's not empty and passed regular expression, connect to db and query it?
![]() |
Mike, 08-21-2009 |
Im trying to learn JQuery, but im stuck with this.
I dont understand what this means or whats the use of this : function(data)
And how will you pass a value to the "data" paramenter. Or where will it get its value
Please help. Thanks
I dont understand what this means or whats the use of this : function(data)
And how will you pass a value to the "data" paramenter. Or where will it get its value
Please help. Thanks
![]() |
Suzanne Cohen, 09-04-2009 |
Could you add a zip file with all your demo code - you reference images and css that arent displayed inline.
thanks
thanks
|
|
Subscribe Now to receive new posts via Email as soon as they come out.
Comments
Post your comments




