Does the following check mean that the field cannot be null? (@Size annotation)

I have the following property in Spring MVC Form bean using javax.validation.constraints to validate the bean form as follows:

 public class MyForm { @Size(min = 2, max = 50) private String postcode; // getter and setter for postcode. } 

My question is: does @Size(min = 2) mean that a property cannot be null since it will always require a length greater than 2. The reason I say this is because there is a @NotNull constraint in the same package and therefore makes the redundant @NotNull restriction redundant if I have to use it in the bean above.

+6
source share
3 answers

If you look at the documentation for Size annotations ( 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 at the top of the field.
You have two alternatives:

 @NotNull @Size(min = 2, max = 50) private Integer age; 

Or as Riccardo F. suggested:

 @NotNull @Min(13) @Max(110) private Integer age; 
+7
source

@NotNull is also used for text fields, but you can use them together, for example

 @NotNull @Min(13) @Max(110) private Integer age; 

This means that age cannot be zero and must have a value between 13 and 100 and

 @NotNull private Gender gender; 

So gender cannot be null

+1
source

According to the documentation for @Size

null are considered valid.

For hibernate-validation reference, actual @Size implementations are in:

org.hibernate.validator.constraints.impl.SizeValidator

So specify @NotNull .

0
source

Source: https://habr.com/ru/post/948227/


All Articles