I have put validation for the following field,
@Min(1)
@Max(500)
private int length;
however, the length isn't a required field but when I didn't give the "length" in the input, I got this error:
"Validation error, message = must be greater than or equal to 1, path = length"
Looking at the @min and @max documentation, it says "null element is considered valid". I know that. If @min @max is only for primitive type, then why the documentation mentions "null" element is considered valid? Can someone let me know how to fix the validation problem? Many thanks.
@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 @NotNull annotation is defined in the Bean Validation specification. This means its usage isn't limited only to the entities. On the contrary, we can use @NotNull on any other bean as well. As we can see, in this case, our system threw javax.
@NotEmpty: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, and its size/length is greater than zero. @NotBlank: a constrained String is valid as long as it's not null, and the trimmed length is greater than zero.
One way we can protect our code is to add annotations such as @NotNull to our method parameters. By using @NotNull, we indicate that we must never call our method with a null if we want to avoid an exception.
For optional integer values, you may use Integer
instead of int
, since an int
variable cannot be null and will have 0 as a default value.
With an Integer
, length will be null by default and you should be able to pass the validation.
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