'How can I check if a number input is not empty?
I have this input field in a form which I validate using spring boot validator:
<input class="form-control" th:field="*{numericField}"
type="number" min="0" id="numeric_field_input">
The valid range is all positive numbers. But even if I do not fill in any number, the field validates. I believe the default value is zero. Adding something like
th:default="-1"
did not solve the problem. How can I check on serverside that a user input any value?
These are my current annotations of the field:
@Positive(message = "{validation.numericField.positive}")
@ColumnDefault("0")
private Integer numericField;
Solution 1:[1]
You can use these 2 validations
@NotNull("message": "numericField: positive number value is required")
@Min(value=0, message="numericField: positive number, min 0 is required")
Solution 2:[2]
You can use min constraint to limit values be only positive numbers
//import javax.validation.constraints.Min;
@Min(value = 0, message = "numericField not be negative")
private Integer numericField;
Solution 3:[3]
Migrating OP's ultimate solution from the question to an answer:
This is the final way how [sic] I fixed it:
@NotNull(message = "{validation.numericField.positive}") @Positive(message = "{validation.numericField.positive}") private Integer numericField;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anish sharma |
| Solution 2 | sanjeevRm |
| Solution 3 |
