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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17344473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:44:46  来源:igfitidea点击:

Does the following validation mean that the field cannot be null? ( @Size annotation )

javavalidationspring-mvc

提问by blackpanther

I have the following property in my Spring MVC Form bean using the javax.validation.constraintsto validate the form bean as follows:

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

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

    // getter and setter for postcode.
}

My question is: Does the @Size(min = 2)mean that the property cannot be nullas it will always require a length greater than 2. The reason why I say that is because there is a @NotNullconstraint in the same package and therefore does that make the @NotNullconstraint redundant if I should use it in the above bean.

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

回答by cloudy_weather

If you look at the documentation of the annotation Size(http://docs.oracle.com/javaee/6/api/javax/validation/constraints/Size.html)

You can read "null elements are considered valid."
Therefore you need to specify @NotNullon the top of your field.
You have two alternatives:

如果您查看注释Size( http://docs.oracle.com/javaee/6/api/javax/validation/constraints/Size.html)的文档,

您可以阅读“空元素被认为是有效的。
因此您需要在字段顶部指定@NotNull
您有两种选择:

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

Or like Riccardo F. suggested:

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

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

回答by Ricardo

@NotNullis used for text fields too but you can use them together like

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

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

That means agecannot be null and must be a value between 13 and 100 and

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

@NotNull
private Gender gender;
@NotNull
private Gender gender;

Means the gendercannot be null

表示性别不能为空

回答by mavarazy

According to documentation for @Size

根据文档 @Size

nullelements are considered valid.

null元素被认为是有效的。

For reference hibernate-validationactual @Sizeimplementations are in:

参考hibernate-validation实际@Size实现在:

org.hibernate.validator.constraints.impl.SizeValidator

org.hibernate.validator.constraints.impl.SizeValidator

So specify @NotNullanyway.

所以@NotNull无论如何都要指定。