@Size注记以验证字段



我需要验证一个字段 - secPhoneNumber (辅助电话#)。我需要使用 JSR 验证满足以下条件

  • 该字段可以为空/空
  • 否则,数据的长度必须为 10。

我尝试了下面的代码。该字段始终在表单提交时得到验证。 如何验证字段的长度仅为 10 时不为空?

弹簧形式:

<form:label path="secPhoneNumber">
Secondary phone number <form:errors path="secPhoneNumber" cssClass="error" />
</form:label>
<form:input path="secPhoneNumber" />

@Size(max=10,min=10)
    private String secPhoneNumber;
我认为

为了可读性和将来的使用,我会创建自定义验证类,您只需按照以下步骤操作:

  1. 将新的自定义注释添加到字段

    @notEmptyMinSize(size=10)
    private String secPhoneNumber;
    
  2. 创建自定义验证类

    @Documented
    @Constraint(validatedBy = notEmptyMinSize.class)
    @Target( { ElementType.METHOD, ElementType.FIELD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface notEmptyMinSize {
    
        int size() default 10;
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }
    
  3. 将业务逻辑添加到验证中

    public class NotEmptyConstraintValidator implements      ConstraintValidator<notEmptyMinSize, String> {
         private NotEmptyMinSize notEmptyMinSize;
         @Override
         public void initialize(notEmptyMinSize notEmptyMinSize) { 
             this.notEmptyMinSize = notEmptyMinSize
         }
         @Override
         public boolean isValid(String notEmptyField, ConstraintValidatorContext cxt) {
            if(notEmptyField == null) {
                 return true;
            }
            return notEmptyField.length() == notEmptyMinSize.size();
        }
    }
    

现在,您可以在多个具有不同大小的字段中使用此验证。

这里有另一个例子,你可以遵循例子

以下模式有效

  1. @Pattern(regexp="^(\s*|[a-zA-Z0-9]{10})$")
  2. @Pattern(regexp="^(\s*|\d{10})$")

// ^             # Start of the line
// s*           # A whitespace character, Zero or more times
// d{10}        # A digit: [0-9], exactly 10 times
//[a-zA-Z0-9]{10}    # a-z,A-Z,0-9, exactly 10 times
// $             # End of the line

参考:仅当字段不为 Null 时才验证

最新更新