Showing posts with label validation. Show all posts
Showing posts with label validation. Show all posts

Tuesday, June 21, 2016

Struts2 Points to remember about “field-validator” nodes

Each field can have one or more “field-validator” nodes

Each fields validators are executed in the order they are defined

Each field validator has a “short-circuit” attribute; if this
is true and the validation fails, all further validations are
skipped and a failed result returned for the field

The message node can include a “key” attribute which
looks up the message to display to the user from a
message bundle; the value of the node is then used if no
message bundle key exists

Validator configuration information (such as min and
max) as well as values from the value stack can be used
in the validation message by placing the value between
the tokens “${“ and “}”

Validators can have a scope of either “field” or
“expression”; expression validators can work across
multiple fields

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');"  />


Monday, January 19, 2015

How to make AJAX call to Struts2 action class method using Wildcard in struts.xml file

STRUTS.XML

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

<interceptors>
<interceptor name="transaction" class="com.raj.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="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>

</package>

ACITON CLASS METHOD

private String packageName;

private InputStream inputStream;


public InputStream getInputStream() {
                return inputStream;
        }
public void setInputStream(String responseText) {
this.inputStream =  new ByteArrayInputStream(responseText.getBytes());

}


public String doValidation(){

PkgData pkgData = PkgDAO.getPkgByName(packageName);

if( packageName==null || packageName.trim().length()==0 ){ 
setInputStream("<div style='color:red;'> Empty Name");

}else if( packageName.matches(NVSMXUtility.NAME_VALIDATION_REGEX_PATTERN) ){ 
if( pkgData != null ){
setInputStream("<div style='color:red;'> Name already exist</div>");
}else{
setInputStream("<div style='color:green;'> Valid Name</div>");
}
        }else{
        setInputStream("<div style='color:red;'> Invalid Name (Only alphanumeric allowed)</div>");
        }
  return Results.SUCCESS;

}

JAVA SCRIPT


function verifyUniqueness(fieldName,actionName){    
 var pkgNameVal = $("#"+fieldName).val();
 $.ajax({
   type: "POST",
   url: '/nvsmx/'+actionName,
   data: {packageName:pkgNameVal},
   success: function(data){    
    $("#message").show();
    $("#message").html(data);
   }
}); 

}


JSP

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

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...