我有一个我要验证的表单。它包含2个地址变量。 address1必须经过验证,address2必须根据某些条件进行验证
I've a form I want to validate. It contains 2 Address variables. address1 has always to be validated, address2 has to be validated based on some conditions
public class MyForm { String name; @Valid Address address1; Address address2; } public class Address { @NotEmpty private String street; }我的控制器会自动验证并绑定我的表单obj
my controller automatically validates and binds my form obj
@RequestMapping(...) public ModelAndView edit( @ModelAttribute("form") @Valid MyForm form, BindingResult bindingResult, ...) if(someCondition) { VALIDATE form.address2 USING JSR 303问题是如果我使用LocalValidatorFactoryBean验证器,我就无法重用Spring提供的BinidingResult对象。绑定不起作用,因为'result'的目标对象是'MyForm'而不是'Address'
the problem is that if I use the LocalValidatorFactoryBean validator i can't reuse the BinidingResult object provided by Spring. The bind won't work as the target object of 'result' is 'MyForm' and not 'Address'
validate(form.getAddress2(), bindingResult) //won't work我想知道什么是标准/干净的方法来进行条件验证。
I'm wondering what's the standard/clean approach to do conditional validation.
我正在考虑以编程方式在我的控制器中创建一个新的BindingResult。
I was thinking in programmatically create a new BindingResult in my controller.
final BindingResult bindingResultAddress2 = new BeanPropertyBindingResult(address2, "form"); validate(form.getAddress2(), bindingResultAddress2);但是我从bindingResultAddress2获得的错误列表无法添加到一般的'bindingResult'中因为字段名称不正确('street'而不是'address2.street')并且绑定不起作用。
but then the List of errors I obtain from bindingResultAddress2 can't be added to the general 'bindingResult' as the field names are not correct ('street' instead of 'address2.street') and the binding won't work.
一些脏方法是扩展BeanPropertyBindingResult接受一些字符串附加到字段名称..你有更好的方法吗?
Some dirty approach would be to extend BeanPropertyBindingResult to accept some string to append to the fields name.. do you have a better approach?
推荐答案验证分层的标准方法结构是使用 pushNestedPath() / popNestedPath(),虽然我不确定它如何与JSR-一起使用303:
The standard approach for validating hierarchical structures is to use pushNestedPath()/popNestedPath(), though I'm not sure how it plays with JSR-303:
bindingResult.pushNestedPath("address2"); validate(form.getAddress2(), bindingResult); bindingResult.popNestedPath();更多推荐
Spring MVC和JSR
发布评论