RSS

Cross field validation using JSR-303

23 Sep

Hi folks,

Here is a post which explains how to implement the class level custom validator using hibernate JSR-303.

Below is the compiled and executed source code.

Controller Class

@RequestMapping(value = “/findAddress”, method = RequestMethod.GET)
public ResponseEntity<String> findAddress(@Validated({FieldMatch.class}) final AddressForm addressForm,
final BindingResult result,
final HttpServletRequest request,final HttpServletResponse response) throws Exception {
if(result.hasErrors()) {
// handling the error messages and send it to jsp page
}
// Here is the logic to invoke the business services
}

AddressForm.java

@FieldMatch.List({
@FieldMatch(first = “isAllCash”, second = “cashAmount”, message = “”, groups=FieldMatch.class)
})
public class AddressForm {
private String isAllCash;
private String cashAmount;
public String getIsAllCash() {
return isAllCash;
}

public void setIsAllCash(final String isAllCash) {
this.isAllCash = isAllCash;
}

public String getCashAmount() {
return cashAmount;
}

public void setCashAmount(final String cashAmount) {
this.cashAmount = cashAmount;
}
}

FieldMatch.java

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

// TODO: Auto-generated Javadoc
/**
* The Interface FieldMatch.
*
*/
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = FieldMatchValidator.class)
@Documented
public @interface FieldMatch
{

/**
* Message.
*
* @return the string
*/
String message() default “{constraints.fieldmatch}”;

/**
* Groups.
*
* @return the class[]
*/
Class<?>[] groups() default {};

/**
* Payload.
*
* @return the class<? extends payload>[]
*/
Class<? extends Payload>[] payload() default {};

/**
* First.
*
* @return The first field
*/
String first();

/**
* Second.
*
* @return The second field
*/
String second();

/**
* Defines several <code>@FieldMatch</code> annotations on the same element.
*
* @see FieldMatch
*/
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Documented
@interface List{
/**
* Value.
*
* @return the field match[]
*/
FieldMatch[] value();
}
}

FieldMatchValidator.java

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.fmr.pi.acs.toa.app.common.AppConstants;

// TODO: Auto-generated Javadoc
/**
* The Class FieldMatchValidator.
*
*
*/
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>{

/** The Constant LOG. */
private static final Log LOG = LogFactory.getLog(FieldMatchValidator.class);

/** The first field name. */
private String firstFieldName;

/** The second field name. */
private String secondFieldName;

/**
* Initialize.
*
* @param constraintAnnotation the constraint annotation
*/
@Override
public void initialize(final FieldMatch constraintAnnotation) {
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}

/**
* Checks if is valid.
*
* @param value the value
* @param context the context
* @return true, if is valid
*/
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context){
try{
final Object fieldName1 = BeanUtils.getProperty(value, firstFieldName);
final Object fieldName2 = BeanUtils.getProperty(value, secondFieldName);
if(fieldName1.equals(AppConstants.EMPTY_STRING) && fieldName2.equals(AppConstants.EMPTY_STRING)){
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(“FieldMatch.addressForm”)
.addNode(secondFieldName).addConstraintViolation();
return false;
}else if(fieldName1.equals(AppConstants.Y) && fieldName2.equals(AppConstants.EMPTY_STRING)){
return true;
}else if(fieldName1.equals(AppConstants.N) && !fieldName2.equals(AppConstants.EMPTY_STRING)){
return true;
}
} catch (final Exception ex){
LOG.error(ex.getMessage());
}
return true;
}
}

Happy Coding!.

Get glued to know more updates.

Have a nice day šŸ™‚

 

Advertisements
 
Leave a comment

Posted by on September 23, 2013 in Uncategorized

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: