如何为可以是两种大小的字段应用大小注释

How to apply size annotation for a field which can be either of two sizes

在我的 spring 启动应用程序中,我对我的 dto 中的一个字段进行了大小验证。现在根据新要求,字段大小可以是 18 或 36。之前是 36,所以我这样做了:

@Size(min=36,max = 36,message = "id length should be 36")

现在我必须针对两种尺寸进行验证,有什么方法可以用注释本身来完成吗?

谢谢,

制作自定义验证器注释。

CustomSize.java

@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = CustomSizeValidator.class)
@Documented
public @interface CustomSize{

  String message() default "{CustomSize.invalid}";

  Class<?>[] groups() default { };

  Class<? extends Payload>[] payload() default { };

}

CustomSizeValidator.java

class CustomSizeValidator implements ConstraintValidator<CustomSize, String> {

   @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
      try { 
        
          if(value.length()==18 || value.length()==36){
              return true;
             }else{
               return false;
             }
        } catch (Exception e) {
         return false;
      }
   }
}

在您的 POJO 代码中使用它。

@CustomSize
private String xyz;

或 使用 @Pattern

@Pattern(regexp = "^(?:[A-Za-z0-9]{18}|[A-Za-z0-9]{36})$")

有关模式,请在此处查看更多信息 ->