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.
Explanation: The @NotNull annotation, which indicates a field cannot be null .
@NotNull: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, but it can be empty.
The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "". It is a character array of zero characters.
@NotNull The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graphs. However, this creates issues for scenarios needing only partial validation.
In Spring, we use JSR-303's @Valid annotation for method level validation. Moreover, we also use it to mark a member attribute for validation. However, this annotation doesn't support group validation. Groups help to limit the constraints applied during validation.
Name cannot be an empty string nor null and address cannot be null. Address class has street and city that cannot be empty nor null and postcode with size between 4 and 6 characters. @Valid annotation comes from Java Bean Validation API mentioned above, lets use it in our controller.
Applying Validation Annotations - Text ¶ To configure validation on the model-side, we begin by adding validation annotations to each field to which we want to apply constraints. For our Event class, we add @Size and @NotBlank to the name field, and just @Size to the description field.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With