Wednesday, January 21, 2015

STRUTS2 AJAX AND JSON BASED VALIDATION

struts.xml

<package name="validationPkg" namespace="/validate" extends="json-default">

<interceptors>
<interceptor name="transaction" class="com.raj.controller.interceptor.TransactionInterceptor" />
</interceptors>

<action name="*/*/*" class="com.raj.controller.{1}.{2}CTRL" method="{3}">
<interceptor-ref name="basicStack"></interceptor-ref>
<interceptor-ref name="transaction"/>
<result type="json">
<param name="root">validationMessage</param>
</result>
</action>

</package>

Action Class

package com.raj.controller.pkg;

public class PkgCTRL extends ActionSupport {

private ValidationMessage validationMessage =  new ValidationMessage();

public ValidationMessage getValidationMessage() {
return validationMessage;
}

public void setValidationMessage(ValidationMessage validationMessage) {
this.validationMessage = validationMessage;
}

public String doValidation(){
LogManager.getLogger().debug(MODULE,"Method called doValidation()");

PkgData pkgData = PkgDAO.getPkgByName(packageName);
getValidationMessage().setMessageCode(ValidationMessage.ERROR);
if( packageName == null || packageName.trim().length() == 0 ){ 
getValidationMessage().setMessage(getText("empty.name"));

}else if( packageName.matches(getText("name.validation.regex")) ){ 
if( pkgData != null ){
getValidationMessage().setMessage(getText("name.already.exist"));
}else{
getValidationMessage().setMessage("Valid Name");
getValidationMessage().setMessageCode(ValidationMessage.SUCCESS);
}
        }else{        
        getValidationMessage().setMessage(getText("invalid.name"));
        }
  return Results.SUCCESS;
}
}

POJO CLASS

public class ValidationMessage {

public final static  short  SUCCESS = 1;
public final static  short  ERROR = 0;

private String message;
private short messageCode;

public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getMessageCode() {
return messageCode;
}
public void setMessageCode(short messageCode) {
this.messageCode = messageCode;
}

}

KEY ENUM


public enum ValidationKeys {

EMPTY_NAME("empty.name"),
NAME_VALIDATION_REGEX("name.validation.regex"),
NAME_ALREADY_EXIST("name.already.exist"),
INVALID_NAME("invalid.name"),
VALID_NAME("valid.name"),;

public String key;
ValidationKeys(String key){
this.key =  key;
}

}

ApplicationResources_en.properties

#Ajax validation messages
invalid.name = Invalid Name (Only alphanumeric Allowed)
empty.name = Empty Name
name.already.exist = Name already exist

name.validation.regex = ^[a-zA-Z0-9]*$

Validation Js file

/* 
 verifyUniqueness() require two arguments 'fieldId' and 'actionName', it makes an AJAX call to the 
 passed action's validation method and it return the appropriate result message.
 Invalid fielId message will be displayed in red color and valid fielId message will be displayed in green color. 
 Here 'actionName' value will be like '/validate/pkg/Pkg/validation'
 in this action value '/validate' is the namespace value in struts.xml file and remaining value will be mapped dynamically to the respective 
 action's method through wildcard used in the struts.xml file.  
 */
function verifyUniqueness(fieldId,actionName){    
 var pkgNameVal = $("#"+fieldId).val();
 clearErrorMessages(null);
 $.ajax({
   type: "POST",
   url: contextPath+actionName,
   data: {packageName:pkgNameVal},    
   success: function(data){                    
    if(data.messageCode == "1"){
    // success code logic
    }else{
                               // error code logic
    }
    callback(data);
   },
   error: function(data){
    console.log(data);
   }
});
}

function callback(data){
 console.log(data);

}

JSP FILE FIELD

<s:textfield name="pkgData.name" key="getText('pkg.name')" id="pkgName" cssClass="form-control" onblur="verifyUniqueness('pkgName','/validate/pkg/Pkg/doValidation');"  />


No comments:

Post a Comment

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...