简体   繁体   English

两个参数的Java Bean验证

[英]Java Bean Validation for two parameters

I have two parameters String firstName and String fullName . 我有两个参数String firstNameString fullName I want to use java bean validation annotation with these parameters. 我想使用这些参数的java bean验证注释。 The trouble is I want this validation to be conditional, if firstName is null then fullName cannot be null and vice versa. 问题是我希望这个验证是有条件的,如果firstName为null则fullName不能为null,反之亦然。 Is there anyway to do this with java bean validation? 无论如何使用java bean验证吗?

If not, what is the best alternative? 如果没有,最好的选择是什么? I could always do the validation in my controller, but I would my application's validation to be uniform mostly handled in our entities/model. 我总是可以在我的控制器中进行验证,但是我的应用程序验证是统一的,主要是在我们的实体/模型中处理。

Currently I have the validation getting done like this 目前我已经完成了这样的验证

if(firstName == null && fullName == null){ if(firstName == null && fullName == null){

throw new ValidationException("either firstName or fullName must be supplied"); 抛出新的ValidationException(“必须提供firstName或fullName”);

} }

If you have a conditional requirement between two properties in a bean, you would need to write a custom class level constraint . 如果bean中的两个属性之间存在条件要求,则需要编写自定义类级别约束 In this case you get passed the whole bean instance into the constraint validator and can implement the conditional logic required. 在这种情况下,您将整个bean实例传递到约束验证器,并可以实现所需的条件逻辑。 This solution is compliant with the Bean Validation specification and hence portable between Bean Validation implementations. 此解决方案符合Bean Validation规范,因此可在Bean Validation实现之间移植。 A Hibernate Validator specific (non portable) solution is to use @ScriptAssert . Hibernate Validator特定(非可移植)解决方案是使用@ScriptAssert

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

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