Monday 20 May 2013

Server Side Validation - Ajax


Let’s take a scenario where server side validation is required to check whether employee is already in a project or not.

Here I'll explain implementation of avove requirement using Ajax in a Struts 2 application but the concept will be same for any other framework.
Step 1: Using JQuery invoke ajax and based on return value display the proper message to user.


$(document).ready(function(){
         $("#associateID").blur(function(){
                var assId =  $("#associateID");
               
   //checkAssociateId function returns true if employee is already available in DB  
        
               if(checkAssociateId(assId.val())){
                          // Display message and set focus on Associate ID field
                          $('#spnassociateID').html('Associate is already On-boarded'); 
                          $('#spnassociateID').css('color', 'red'); 
                          $('#spnassociateID').css( 'font-size', 'small'); 
                          $("#associateID").focus();
                          return false;
                } else{                      
                         
                          $('#spnassociateID').html('ID is accepted and not available in project data base'); 
                          $('#spnassociateID').css('color', 'green'); 
                          $('#spnassociateID').css( 'font-size', 'small'); 
                           return true;                         
                }          
         })
       })

function
checkAssociateId(id){
        //checkAssociateAjaxCall returns "not-available" if associate id is not present in employee_details
       var
result = checkAssociateAjaxCall(id);
       if
(result.indexOf("not-available")>=0){
            return
false;
       }else
{
            return
true;
   }
}

// checkAssociateAjaxCall actually do the Ajax call
function
checkAssociateAjaxCall(id)
{
// Ajax implementation
    var
result;
    var
xmlhttp;
// random parameter is added to make each request unique other wise cache will automatically take previous result without hitting DB
    var
strURL = "validateAssociateId?associateId="+ id + "&random=" + Math.random(); ;
  if
(window.XMLHttpRequest)
   {
// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=
new XMLHttpRequest();
   }
   else
 {
// code for IE6, IE5
        xmlhttp=
new ActiveXObject("Microsoft.XMLHTTP");
  }
        xmlhttp.onreadystatechange=
function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
      result = xmlhttp.responseText;
}
}
   xmlhttp.open(
"GET",strURL,false);
  xmlhttp.send();
  return result;
}

Step 2: In Above code calling "validateAssociateId" action thus add below piece of code in struts configure xml (struts.xml).

<
action name="validateAssociateId"
class="com.assetman.action.OnboardEmployeeAction" method="validateAssociateId" >
           <result type="stream">
             <param name="contentType">text/html</param>
             <param name="inputName">inputStream</param>
          </result></action>
Step 3:  In OnboardEmployeeAction struts action class define followings

private static String BLANK ="";// declare a inputStream and gette setter for in
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
Step 4: In OnboardEmployeeAction struts action class define validateAssociateId method

@SuppressWarnings("deprecation")
public String validateAssociateId() throws Exception{

   String result=
BLANK;
// ValidateTask calls validateAssociateId method which returns either "success" or "error"
// PLease implement back end code as per your requirement
  ValidateTask validateTask =  new ValidateTask();
  result = validateTask.validateAssociateId( associateId);
if(result.equals(SUCCESS)){
// inputStream = new ByteArrayInputStream("available".getBytes("UTF-8"));
inputStream = new StringBufferInputStream("available");
}
else{
// inputStream =new ByteArrayInputStream("not-available".getBytes("UTF-8"));
inputStream = new StringBufferInputStream("not-available");
}
return SUCCESS;
}