Would you like to be notified for every new articles? Please click HERE to subscribe for newsletter.

JQuery Ajax Validation Plugin

  • Posted on: 15 May 2015
  • By: admin

The jQuery form plugin by malsup is an excellent plugin when we want to use Ajax feature when submitting the web form. It will be more cool if we can add validation feature to mark the fields which contain error. For security reason, the validation itself will be done in server side not in client side. This plugin is intended to achive that. By using this plugin we can mark the invalid field content by giving a different background color using CSS, add an error message besides the invalid fields, or even displaying loader while the form submission is being processed and validated. Because it's related to the server side script, we must prepare our server side script to return the JSON data whether the submitted data is valid or not.

Firstly, you can see the demo there. And then please take a look at the following code that construct our front-end.

<!DOCTYPE html>
<html>
<head>
  <title>Ajax Form Validation</title>
  <script src="js/jquery.js"></script>
  <script src="js/jquery.form.js"></script>
  <script src="js/jquery.ajaxvalidation.js"></script>
  <link rel="stylesheet" type="text/css" href="css/jquery.ajaxvalidation.css" />
</head>
<body>
  <div id="message"></div>
  <br/>
  <form id="form1" action="action.php" method="post">
    Name :<br/>
    <input type="text" name="name" /><br/>
    Address :<br/>
    <input type="text" name="address" /><br/>
    Photo :<br/>
    <input type="file" name="photo" />
    <br/><br/>
    <input type="submit" name="submit" value="SAVE" />
  </form>
  <br/>
  <p><i>* All validation is done in server.</i></p>
  <script>
    $(document).ready(function() {
      $('#form1').ajaxvalidation({
        errorChar:"[field-message]",
        onComplete: function(result) {
          if(result.status=="success"){
            alert("Your data is valid.");
          }
        }
      });
    });
  </script>
</body>
</html>

And the following code is our server side script which will do the validation.


<?php
if(isset($_POST['submit'])){
  
// For delay effect
  
sleep(1);

  

// For storing the error fields' name
  
$errorFields = array();
  
// Validate fields
  
if($_POST['name']==""){
    
// Array key must be the same like input name.
    
$errorFields['name'] = "Please fill name!";
  }
  if(
$_POST['address']==""){
    
// Array key must be the same like input name.
    
$errorFields['address'] = "Please fill address!";
  }

  

// Check error fields count
  
if(count($errorFields)==0){
    
// Success message
    
$result['status'] = "success";
    
$result['message'] = "Your data has been saved.";
    
// Form will be cleared
    
$result['clearForm'] = true;
  }
  else{
    
// Failed message
    
$result['status'] = "failed";
    
$result['message'] = "Please fill all fields correctly!";
    
// Form will not be cleared
    
$result['clearForm'] = false;
  }

  

// Error fields list
  
$result['errorFields'] = $errorFields;

  

// Return message and error fields is JSON format
  
echo json_encode($result);
}
?>

We also need to ad some style using the following CSS. Please remember that the CSS can be customize to fit our needs.

.error-field-char{
  color:#f00;
}
 
.error-field-background{
  background-color:#ffc;
}
 
#waiting{
  background-color:#ffc;
  border:1px solid #eeb;
  padding: 3px;
}
 
.success{
  color:#369;
  font-weight:bold;
}
 
.failed{
  color:#933;
  font-weight:bold;
}

Let's break the important part of our code from the front end first. Look at the way we activate the plugin with the following code.

$(document).ready(function() {
  $('#form1').ajaxvalidation({
    errorChar:"[field-message]",
    onComplete: function(result) {
      if(result.status=="success"){
        alert("Your data is valid."); 
      }
    }
  });
});

For the default, using only $('#form1').ajaxvalidation() is enough, but with some options coming along with this plugin, we can get a more sophisticated outcome. For the example, the errorChar option will be used as a marker for the error fields. We can replace it with our custom message from server side script by using [field-message]. We can use onComplete option to put our callback function when the submission process is completed. With this callback function we are able to get the variable returned by the server side script.

Of course there are other configurable options such as:

  • messageDivId, the HTML element (could be DIV or any other) for containing the returned validation message (default = "message").
  • waitingDivId, place for us to put the waiting message when the form submission is in progress (default = "waiting").
  • loadingMessage, the loading message when the form is being submitted (default = "Loading...").
  • onError, callback function when there is error on request (default = null).
  • selector, the default selector for form element (default = "name").

Now, let's move on to our server side script. We can see that there are some fixed keys for the array that will be return by the script such as:

  • status, the value should be 'success' or 'failed' to indicate that the submitted data is valid or not.
  • message, for containing the validation message.
  • clearForm, its value should be 'true' or 'false' to instruct the plugin to clear the form or not after the submission process is completed.
  • errorFields, will be containing associative array of the error fields. The keys name should be the same like the default selector for the form input fields. In this case the keys name should be the same like the form input name.

That's all. You can download the source code from the following link.
https://github.com/w3shaman/jquery-ajax-validation.
Please feel free to contact me if you want to make any contribution for this small project.

Add new comment

Limited HTML

  • Allowed HTML tags: <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.