关于javax.validation
@NotNull(message = "From can't be null")
@Min(value = 1, message = "From must be greater than zero")
private Long from;
@NotNull(message = "To can't be null")
@Min(value = 1, message = "To must be greater than zero")
private Long to;
我还想确认 FROM 应小于 TO , TO 应大于 FROM ?我们如何使用javax验证注释来做到这一点?
答案 0 :(得分:0)
您需要自定义cross field validation
注释。
一种方法是使用@YourCustomAnnotation
注释您的自定义类。
在YourCustomAnnotationValidator
中,您可以访问您的值,因此您可以在那里实现您的逻辑:
@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;
}
}
然后使用YourDto
@RangeCheck
课程
@RangeCheck(message = "your messgae")
public class YourDto {
// from
// to
}
或者只是手动验证两个字段的关系。