Melis
Melis

Reputation: 85

Hibernate Validator generic and cross-parameter constraint parameter passing

I want to check whether the value in startDate field is "before" the value endDate field. This is my Bean class:

@AfterStartDate({"startOfDilation","endOfDilation"})
public class MyBean{ 
    private Date startDate,
    private Date stopDate,
    ...
}

The annotation gives the error "Cannot find method value". Do I define it right? I want to use this annotation for other bean classes too. So, that's why I don't want to use MyBean class to pass values to Annotation class.

AfterStartDate.java

@Target({ ElementType.METHOD, ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = AfterStartDateValidator.class)
public @interface AfterStartDate {
    String message() default "{AfterStartDate.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

AfterStartDateValidator.java

@SupportedValidationTarget(ValidationTarget.PARAMETERS)
public class AfterStartDateValidator implements ConstraintValidator<AfterStartDate,Object[]> {

    @Override
    public void initialize(AfterStartDate constraintAnnotation) {
    }

    @Override
    public boolean isValid(Object[] value, ConstraintValidatorContext context){
        if ( value.length != 2 ) {
            throw new IllegalArgumentException( "Illegal method signature" );
        }

        //leave null-checking to @NotNull on individual parameters
        if ( value[0] == null || value[1] == null ) {
            return true;
        }

        if ( !( value[0] instanceof Date ) || !( value[1] instanceof Date ) ) {
            throw new IllegalArgumentException(
                "Illegal method signature, expected two " +
                        "parameters of type Date."
            );
        }

        return ( (Date) value[0] ).before( (Date) value[1] );
       }
   }

Upvotes: 0

Views: 2824

Answers (1)

Guillaume Smet
Guillaume Smet

Reputation: 10529

So, the issue you have with your IDE is that you define a value for your annotations but you don't have a value() attribute defined in your annotation.

But this is your less pressing issue.

What you want is a class level constraints and you're using a cross parameter one hoping it will do what you want. It won't.

To do what you want to do, you need:

Upvotes: 2

Related Questions