Skip to main content

Using Ajax to Validate Forms

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;        }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:

  1. Only if the value has changed run the check, i.e. ignore meta keys
  2. Use a nice ajax spinner to indicate activity
  3. 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;    }  });});Finally, put the current value in to a cache, to make sure we ignore meta keys (from above).

Server response

Now all I have to add to the PHP code, that already handles normal username validation is:

if (@$_REQUEST['action'] == 'check_username' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {    echo json_encode(check_username($_REQUEST['username']));    exit; // only print out the json version of the response}

So long as this is high enough in the logic, it will just check the
username is valid, using our existing function and convert the response
to a JSON object (you may need to add JSON support for PHP, otherwise it’s bundled with PHP 5.2.0).Ref: http://jqueryfordesigners.com/using-ajax-to-validate-forms/