问题描述
我使用 spring boot 验证器验证的表单中有这个输入字段:
<input class="form-control" th:field="*{numericField}"
type="number" min="0" id="numeric_field_input">
有效范围均为正数。但即使我不填写任何数字,该字段也会生效。我相信默认值为零。添加类似
th:default="-1"
编辑:这些是我当前对该字段的注释:
@Positive(message = "{validation.numericField.positive}")
@ColumnDefault("0")
private Integer numericField;
编辑2: 这是我修复它的最终方法:
@NotNull(message = "{validation.numericField.positive}")
@Positive(message = "{validation.numericField.positive}")
private Integer numericField;
解决方法
您可以使用这两个验证
@NotNull("message": "numericField: positive number value is required")
@Min(value=0,message="numericField: positive number,min 0 is required")
,
您可以使用 min
约束来限制值只能是正数
//import javax.validation.constraints.Min;
@Min(value = 0,message = "numericField not be negative")
private Integer numericField;