Search code examples
javahibernateaspectjbean-validationhibernate-validator

Using Hibernate (JSR 303) method validation to compare parameters


I'm using JSR303 method validator extensivly to validate the inputs to my service layer automaticaly with a little help fron aspectj. One thing that is surely missing is the ability to do cross parameter validation, i.e. for example compare two date parameters. How can I achieve that with hibernate method validation ? Is it possible ? Any other recommended way to address this ?

This is the current code of my aspect

public abstract aspect ValidationAspect {
@Inject
private Validator validator;

protected ParameterValidationError[] validateParameters(
        JoinPoint jp) {         
    MethodSignature methodSignature = (MethodSignature)jp.getSignature();
    Method targetMethod = methodSignature.getMethod();
    Object targetObj = jp.getThis();
    Object[] args = jp.getArgs();
    String[] names = ((CodeSignature)jp.getSignature()).getParameterNames();        

    MethodValidator methodValidador = validator.unwrap(MethodValidator.class);
    Set<? extends MethodConstraintViolation<?>> validationErrors = methodValidador.validateAllParameters(                       
            targetObj,
            targetMethod,
            args);

    ParameterValidationError[] output = new ParameterValidationError[validationErrors.size()];
    int idx = 0;
    for (MethodConstraintViolation<?> mcv : validationErrors ) {
        output[idx++] = new ParameterValidationError(
                mcv.getParameterIndex(),
                names[mcv.getParameterIndex()],
                mcv.getInvalidValue(),
                mcv.getMessage());          
    }   

    return output;
}   

}


Solution

  • Hibernate Validator's method level validation does not allow cross parameter validation. It implements method validation as specified in the appendix C of Bean Validation 1.0.

    Part of the ongoing discussion for Bean Validation 1.1 is whether and how to support this feature. See also