You need a custom cross field validation
annotation.
One way is to annotate your custom class with @YourCustomAnnotation
.
In YourCustomAnnotationValidator
you have access to your value, hence you can implement your logic there:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Constraint(validatedBy = DateValidator.class)
public @interface RangeCheck {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class RangeCheckValidtor implements ConstraintValidator<RangeCheck, YourDto> {
@Override
public void initialize(RangeCheck date) {
// Nothing here
}
@Override
public boolean isValid(YourDto dto, ConstraintValidatorContext constraintValidatorContext) {
if (dto.getFrom() == null || dto.getTo() == null) {
return true;
}
return from < to;
}
}
Then mark your YourDto
class with @RangeCheck
:
@RangeCheck(message = "your messgae")
public class YourDto {
// from
// to
}
Or simply manually validate the relation of two fields.