Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java validation @min @max annotion for null values

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.

like image 413
jlp Avatar asked Sep 29 '17 17:09

jlp


People also ask

What is @NotNull annotation in Java?

@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.

What does @NotNull annotation mean in bean property?

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.

What is difference between @NotEmpty and @NotBlank?

@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.

What is @NotNull annotation in spring boot?

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.


1 Answers

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.

like image 76
Thibault Seisel Avatar answered Oct 10 '22 18:10

Thibault Seisel