Using Ajax to Validate Forms

Forms are such a common element on the Internet we tend to blunder through them without too much thought. However, if the web site has added a few nice touches that make the process easier, it tends to speed up the process and reduce any frustration in finding our preferred username (i.e. try getting your name under Hotmail!).

Howto
As with all these tutorials, I expect that you have built your solution to the point where it works, but now we want to add our splash of JavaScript magic.
In our baseline example, my requirements are:
  • Username validation kept in separate function
  • Server side does the it’s normal job
  • I can detect an Ajax request and return something different
Username validation
Our PHP function to validate the username reads:




function check_username($username) {
$username = trim($username); // strip any white space
$response = array(); // our response

// if the username is blank
if (!$username) {
$response = array(
'ok' => false,
'msg' => "Please specify a username");


// if the username does not match a-z or '.', '-', '_' then
  // it's not valid
} else if (!preg_match('/^[a-z0-9\.\-_]+$/', $username)) {
$response = array(
'ok' => false,
'msg' => "Your username can only contain alphanumerics and period,
                  dash and underscore (.-_)");

// this would live in an external library just to check if the username is taken
} else if (username_taken($username)) {
$response = array(
'ok' => false,
'msg' => "The selected username is not available");

// it's all good
} else {
$response = array(
'ok' => true,
'msg' => "This username is free")
;
}

return $response;
}


This format for a response is good, because we are using it to display error messages on the page, but we can also convert it to JSON and use it in our Ajax response later on.


Markup

Again, it’s assumed your markup is already designed to show error messages.

For this example the following markup is being used within a fieldset.

<div>
<label for="username">Username, valid: a-z.-_</label>
<input type="text" name="username" value="<?=@$_REQUEST['username']
                   ?>" id="username" />
<span id="validateUsername"><?php if ($error) { echo $error
                   ['msg']; }?></span>
</div>

jQuery

Our client side check will perform the following:

  • Only if the value has changed run the check, i.e. ignore meta keys
  • Use a nice ajax spinner to indicate activity
  • Make an Ajax request and show the response




$(document).ready(function () {
var validateUsername = $('#validateUsername');
$('#username').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass('error').html
                                    ('<img src="images/ajax-loader.gif"
                      height="16" width="16" /> checking availability...');
this.timer = setTimeout(function () {
$.ajax({
url: 'ajax-validation.php',
data: 'action=check_username&username=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validateUsername.html(j.msg);
}
});
}, 200);

this.lastValue = this.value;
}
});
});


Fire an ajax request in 1/5 of a second.


$.ajax({
url: 'ajax-validation.php',
data: 'action=check_username&username=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validateUsername.html(j.msg);
}
});

The actual Ajax request. If the script ajax-validation.php returns any response, convert it to JSON and put the ‘msg’ field in to the validation message.

Ajax Validation code : Download

If you have better solution, just tell me !

0 comments: