@Size annotation to validate a field
Asked Answered
T

2

2

I need to validate a field - secPhoneNumber (secondary phone #). I need to satisfy below conditions using JSR validation

  • The field can be empty/null
  • Otherwise, the data must be of length 10.

I tried the code below. The field is always getting validated on form submission. How do I validate the field to be of length 10 only when it is not empty?

Spring Form:

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

Bean

@Size(max=10,min=10)
    private String secPhoneNumber;
Thomasthomasa answered 6/7, 2016 at 13:3 Comment(4)
Should me @Length for a String. And it is not checked when the value is null.Stibine
Mengelle, Thanks for your input. Tried using @Length(max=10,min=10) private String secPhoneNumber , but doesn't fulfill the use case.Thomasthomasa
Sorry, @Size was valid with javax.validation, but not hibernate validator. I don't know what you use. Anyway, if your need is : not required, but when provided the length = 10 (it is what i understood), this should be ok. Note that an empty string is considered as a value, so the @Size will be trigered. You need null value if not provided, then the validation will not be trigerred. For more details : #11550824Stibine
Adjusted code formatting; cleaned up rhetoric.Sultry
S
2

I think for readability and to use in future times i would create my custom validation class, you only should follow this steps:

  1. Add your new custom annotation to your field

    @notEmptyMinSize(size=10)
    private String secPhoneNumber;
    
  2. Create the custom validation classes

    @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. Add your business logic to your validation

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

And now you could use this validation in several fields with different sizes.

Here another example you can follow example

Scanty answered 7/7, 2016 at 11:5 Comment(0)
T
1

Following patterns work

  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

Reference: Validate only if the field is not Null

Thomasthomasa answered 7/7, 2016 at 3:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.