1

フィールドを検証する必要があります-secPhoneNumber(セカンダリ電話番号)。JSR検証を使用して以下の条件を満たす必要があります

  • フィールドは空/null にすることができます
  • それ以外の場合、データの長さは 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;
4

2 に答える 2

2

読みやすさと将来的に使用するために、カスタム検証クラスを作成すると思います。次の手順のみを実行する必要があります。

  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();
        }
    
    }
    

これで、サイズの異なる複数のフィールドでこの検証を使用できるようになりました。

ここでは、例に従うことができる別の例を示します

于 2016-07-07T11:05:35.993 に答える
1

次のパターンが機能します

  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でない場合のみ検証する

于 2016-07-07T03:01:41.870 に答える