【问题标题】:Validating integer field in DTO验证 DTO 中的整数字段
【发布时间】:2021-06-29 05:18:15
【问题描述】:

我的 Spring Boot 应用程序具有以下 DTO 请求:

public class MyAwesomeDTO {

    @NotNull
    private Integer itemCount;
}

我希望 itemCount 为 0 或在 [3, 10] 范围内 .后者可以通过@Min(3) @Max(10) 进行验证,但是如何验证“OR”条件呢?

【问题讨论】:

    标签: spring spring-boot hibernate-validator


    【解决方案1】:

    itemCount0null 之间存在差异。 @NotNull 只防范 null,而不是 0

    完成您需要的最简单的方法是编写自定义验证器。

    首先创建一个自定义注解来触发验证:

    @Target( { ElementType.METHOD, ElementType.FIELD })
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = ItemCountValidator.class)
    public @interface ValidItemCount {
        String message() default "Invalid item count";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }
    

    接下来,创建自定义验证器:

    public class ItemCountValidator implements 
      ConstraintValidator<ValidItemCount, Integer> {
    
        @Override
        public void initialize(ValidItemCount validItemCount) {
        }
    
        @Override
        public boolean isValid(Integer itemCount,
          ConstraintValidatorContext cxt) {
            return itemCount != null && (itemCount == 0 || itemCount > 3 && itemCount < 10);
        }
    
    }
    

    最后,更新你的 DTO:

    public class MyAwesomeDTO {
    
        @ValidItemCount
        private Integer itemCount;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多