Java validation @min @max annotion for null values
Asked Answered
A

1

8

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.

Autolysin answered 29/9, 2017 at 17:0 Comment(5)
And when do you expect length to be null?Bashaw
I didn't expect it to be null. I just don't know how to pass the validation when length is not provided. I thought ""null element is considered valid" meant the scenario of "not provided"Autolysin
An int can't ever be null, it's a primitive type. If you want it to be nullable, you have to make it an Integer.Nga
When you don't expect it to be null, then why do you quote that line? And the "min" annotation makes it quite clear that you can't pass validation when you don't provide a proper value.Bashaw
"If min max is only for primitive type" - That assumption is wrong.Bashaw
K
13

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.

Katzenjammer answered 29/9, 2017 at 17:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.