javax验证大于或小于其他属性

时间:2018-05-24 06:12:42

标签: java validation javax

关于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验证注释来做到这一点?

1 个答案:

答案 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
}

或者只是手动验证两个字段的关系。