jQuery: detecting validation messages in Ajax

Ajax responses are usually very simple to handle. Generally speaking, all you have to do is inserting the content of the response into the DOM. But sometimes they can be quite complex. Suppose that you have to perform a form validation with Ajax. The served-side language can either return a list of validation errors or a message indicating that the user has sent the form successfully. How can you choose between these two types of messages?

I found a simple solution: for validation errors, I wrap the message inside the following HTML element.

<div class="error" rel="label"></div>

As you can see, I use the CSS class error as an internal flag. Instead, the rel attribute has a value that corresponds to the ID of the form field that needs to be highlighted. In my particular case, I've chosen to highlight its corresponding label element instead. On the contrary, the wrapper for successful responses is much simpler:

<div class="success"></div>

However, there's a catch: I usually serve my responses as text/plain, since they're considerably faster to load. What I really need is a function that parses error messages and another that inserts the message into the DOM. Here they are:

var parseValidationErrors = function(html) {
    
       var errorList = $('<div class="error-list"></div>');
       errorList.appendTo('#main');
       errorList.html(html);
    
       var lines = html.split('\n');
       var attributes = [];
       
       for(var i=0; i<lines.length; i++) {
       
           var line = lines[i];
    var attrRe = /rel=".+"/;
    
    if(attrRe.test(line)) {
    
        var match = line.match(attrRe);
        
        var rawAttr = match[0];
        
        var attr = rawAttr.replace('rel="', '').replace('"', '');
        
        attributes.push(attr);
    
    }
       
       }
       
       for(var j=0; j<attributes.length; j++) {
       
           var rel = attributes[j];
    var id = '#' + rel;
    
    $(id).prev().addClass('error-label');
       
       }
       
    
    };
    
    var parseSuccessMessage = function(target, html) {
    
        $(target).replaceWith(html);
    
    };

parseValidationErrors() uses regular expressions to find and extract the value of the rel attribute from the Ajax response, whereas parseSuccessMessage() simply replace an existing portion of the DOM with the Ajax content. Now we need a third function that is actually able to detect the type of message returned and act accordingly:

var detectResponseType = function(html) {
    
    var errorClass = /class="error"/;
 
 if(errorClass.test(html)) {
     return false;
     
 } else {
 
     return true;
     
 }
    
    
};

This function only tests whether the message returned contains the CSS class error. Now we can put it all together:

$('#testForm').submit(function(e) {
 
     var data = 'test=foo&bar=baz';
     
     $.ajax({
       type: 'POST',
       url: 'ajax.php',
       data: data,
       success: function(html) {
       
    
  if(detectResponseType(html)) {
  
      parseSuccessMessage('#test', html);
      
  } else {
      
      parseValidationErrors(html);
      
  }
    
       
       }
       
     });
     
     e.preventDefault();
 
});

Leave a Reply

Note: Only a member of this blog may post a comment.