简体   繁体   English

JSR303-仅在填充时验证

[英]JSR303 - Validate Only if Populated

I have a field in a Java Bean (kilograms) that is not mandatory, but if the user does enter it, it obviously needs to be a number. 我在Java Bean中有一个不是强制性的字段(千克),但是如果用户输入了它,则显然必须是一个数字。

Is there a combination of JSR303 annotations that can enforce that rule? 是否可以组合执行该规则的JSR303批注? I tried 我试过了

@Min(value=0)

But that obviously disallows empty, which is allowable. 但这显然不允许空的,这是允许的。

Thanks for any help. 谢谢你的帮助。

The documentation says that null values are considered valid. 该文档说,空值被认为是有效的。 See 看到

http://jackson.codehaus.org/javadoc/bean-validation-api/1.0/javax/validation/constraints/Min.html http://jackson.codehaus.org/javadoc/bean-validation-api/1.0/javax/validation/constraints/Min.html

You need to use object types (Integer) instead of primitive types. 您需要使用对象类型(整数)而不是原始类型。 If you have problems with it please show us your bean. 如果您有问题,请向我们展示您的bean。

You cannot do a OR composition with Bean Validation 1.0. 您不能使用Bean Validation 1.0进行OR合成。 Hibernate Validator has a feature which allows you do so. Hibernate Validator具有一项允许您执行此操作的功能。 It is called "boolean composition of custom constraints" - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#d0e3701 这称为“自定义约束的布尔组成”-http: //docs.jboss.org/hibernate/stable/validator/reference/zh-CN/html_single/#d0e3701

So you need a custom constraint and you obviously won't be standard conform, but it works. 因此,您需要一个自定义约束,并且显然不会符合标准,但它可以工作。

For Bean Validation 1.1 there is a discussion whether boolean composition should make it into the standard ( BVAL-260 ), but it is not guaranteed. 对于Bean Validation 1.1,存在关于布尔组合是否应使其成为标准( BVAL-260 )的讨论,但不能保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM