I need to validate a field - secPhoneNumber (secondary phone #). I need to satisfy below conditions using JSR validation
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;
I think for readability and to use in future times i would create my custom validation class, you only should follow this steps:
Add your new custom annotation to your field
@notEmptyMinSize(size=10)
private String secPhoneNumber;
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 {};
}
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