Reputation: 11486
I have the following property in my Spring MVC Form bean using the javax.validation.constraints
to validate the form bean as follows:
public class MyForm {
@Size(min = 2, max = 50)
private String postcode;
// getter and setter for postcode.
}
My question is: Does the @Size(min = 2)
mean that the property cannot be null
as it will always require a length greater than 2. The reason why I say that is because there is a @NotNull
constraint in the same package and therefore does that make the @NotNull
constraint redundant if I should use it in the above bean.
Upvotes: 26
Views: 23394
Reputation: 7735
According to documentation for @Size
null
elements are considered valid.
For reference hibernate-validation actual @Size
implementations are in:
org.hibernate.validator.constraints.impl.SizeValidator
So specify @NotNull
anyway.
Upvotes: 2
Reputation: 2977
If you look at the documentation of the annotation Size (http://docs.oracle.com/javaee/6/api/javax/validation/constraints/Size.html)
You can read "null elements are considered valid."
Therefore you need to specify @NotNull on the top of your field.
You have two alternatives:
@NotNull
@Size(min = 2, max = 50)
private Integer age;
Or like Riccardo F. suggested:
@NotNull @Min(13) @Max(110)
private Integer age;
Upvotes: 33
Reputation: 67
@NotNull is used for text fields too but you can use them together like
@NotNull @Min(13) @Max(110) private Integer age;
That means age cannot be null and must be a value between 13 and 100 and
@NotNull private Gender gender;
Means the gender cannot be null
Upvotes: 2