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
Does the following validation mean that the field cannot be null? ( @Size annotation )
提问by blackpanther
I have the following property in my Spring MVC Form bean using the javax.validation.constraints
to 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 null
as it will always require a length greater than 2. The reason why I say that is because there is a @NotNull
constraint in the same package and therefore does that make the @NotNull
constraint 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
null
elements are considered valid.
null
元素被认为是有效的。
For reference hibernate-validationactual @Size
implementations are in:
参考hibernate-validation实际@Size
实现在:
org.hibernate.validator.constraints.impl.SizeValidator
org.hibernate.validator.constraints.impl.SizeValidator
So specify @NotNull
anyway.
所以@NotNull
无论如何都要指定。