Friday 25 May 2012

CustomValidation using Annotation in Struts

While doing the validation, the developer can write his own custom validation to validate the fields. In Struts2 it can be done by using @CustomValidator. The Custom Validator takes mandatory fields as:
1. type - it is the name to the validator which will be defined in the validation.xml
2. message - it is the message which you would like to show on the validation failure.
3.fieldName - this will be necessary if you are not defining the validator above the field name. In the below example i have used the validator at the class level so its necessary to mention the name of the validator.


A custom validator can be implemented by implementing the FieldValidatorSupport or the ValidatorSupport. Below is the example to write a custom validator.


-----------------------------------------------------------------------
PhoneNumberValidator.java :
-----------------------------------------------------------------------

package com.lntinfotech.office.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

public class PhoneNumberFieldValidator extends FieldValidatorSupport {
private Logger logger=LoggerFactory.getLogger(getClass());
public void validate(Object object) throws ValidationException {

String fieldName = getFieldName();
Object value = this.getFieldValue(fieldName, object);

if (!(value instanceof String)) {
return;
}

String str = ((String) value).trim();
try{
if (str.length() != 0) {
if (str.indexOf("-", 0) <= 5) {
if (str.indexOf("-") == str.lastIndexOf("-")) {
String stdcode = str.substring(0, str.indexOf("-"));
String phoneNo = str.substring((str.indexOf("-") + 1));
if(phoneNo.length()<6){
addFieldError(fieldName, object);
}
try {
Integer.parseInt(stdcode);
Integer.parseInt(phoneNo);
} catch (NumberFormatException nfe) {
addFieldError(fieldName, object);
logger.error("<-- validate(Object object) :"+nfe);
return;
}

return;
}
}

}
}catch(Exception e ){
addFieldError(fieldName, object);
logger.error("<-- validate(Object object) :"+e);
return;
}
}
}


note:


The fieldName and getFieldValue are implemented in superclass and are used to retrieve the name and value of the field getting validated respectively.
The addFieldError method is used to add any failed validations to the list of error to be displayed.
-----------------------------------------------------------------------


The validators.xml is used to map the validator class with a name which will be used in the class which will request validation.
-----------------------------------------------------------------------
validators.xml
-----------------------------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
     "-//OpenSymphony Group//XWork Validator Config 1.0//EN"
     "http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
 <validator name="phoneNumberFieldValidator" class="com.lntinfotech.office.common.PhoneNumberFieldValidator"/>
</validators>
-----------------------------------------------------------------------


In the below class we will be validating the phone number using the custom validator. I have removed various other fields from the class as its not necessary. For validating the field either you can define the validation at the class level as I have done below or can be done on the getter method of the field. for doing the validation at the getter method you need to define the validator just above the getter method.


-----------------------------------------------------------------------
RegistrationAction.java
-----------------------------------------------------------------------


package com.lntinfotech.office.controller;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.CustomValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

@ParentPackage(value = "office")
@InterceptorRef("jsonValidationWorkflowStack")
@Validations(
customValidators = { @CustomValidator(fieldName = "phoneNo", message = "Please enter the phone number in STD-Phone(XXX-XXXXXX) Format", type = "phoneNumberFieldValidator") })
public class RegistrationAction extends ActionSupport {
private static final long serialVersionUID = 1L;

private Logger logger = LoggerFactory.getLogger(getClass());

private String phoneNo;
public String getPhoneNo() {
return phoneNo;
}

public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}

@Action(value = "/createuser", results = {
@Result(location = "registrationSuccess.jsp", name = "success"),
@Result(location = "registration.jsp", name = "input"),
@Result(location = "registration.jsp", name = "error") }, className = "registerUser")
public String createUser() {
logger.debug("--> createUser()");
return "success";
}

}

-----------------------------------------------------------------------

No comments:

Post a Comment