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;
@Length
for a String. And it is not checked when the value is null. – Stibine@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 : #11550824 – Stibine