以下验证是否意味着该字段不能为 null?( @Size 注释 )

2022-09-02 03:39:46

我在我的春季MVC表单bean中有以下属性,使用来验证表单bean,如下所示:javax.validation.constraints

public class MyForm {
    @Size(min = 2, max = 50)
    private String postcode;

    // getter and setter for postcode.
}

我的问题是:这是否意味着属性不能,因为它总是需要大于2的长度。我之所以这么说,是因为在同一个包中有一个约束,因此,如果我在上面的bean中使用它,那么约束是多余的。@Size(min = 2)null@NotNull@NotNull


答案 1

如果您查看注释大小http://docs.oracle.com/javaee/6/api/javax/validation/constraints/Size.html

的文档,则可以阅读“null元素被视为有效”。
因此,您需要在字段顶部指定@NotNull
您有两种选择:

@NotNull 
@Size(min = 2, max = 50)
private Integer age;

或者就像Riccardo F.建议的那样:

@NotNull @Min(13) @Max(110)
private Integer age;

答案 2

@NotNull也用于文本字段,但您可以一起使用它们,例如

@NotNull @Min(13) @Max(110)
private Integer age;

这意味着年龄不能为空,并且必须是介于 13 和 100 之间的值

@NotNull
private Gender gender;

表示性别不能为空


推荐