简体   繁体   English

基于Spring注释的表单验证

[英]Spring Annotation Based Form Validation

I'm using Springs annotations based form validation (mainly @NotBlank and @Length) which works great. 我正在使用基于Springs注释的表单验证(主要是@NotBlank和@Length),效果很好。 I'm passing the formbean into the validation method like so: 我正在将formbean传递到验证方法中,如下所示:

validate(formBean, result);

I have several annotations attached to various form fields which are validating as expected apart from one. 我有几个批注附加到各种表单字段,除了一个之外,它们都按预期进行验证。

One of my fields in the form bean is declared like so: 我在bean表单中的一个字段声明如下:

private EntriesBean entries;

This field obviously refers to a bean which has the usual getters and setters. 显然,该字段是指具有通常的getter和setter方法的bean。 A couple of the fields within this bean also have the validation annotations attached but they do not validate as part of the validate() method call like the other fields do. 此bean中的几个字段还附加了验证批注,但它们不像其他字段那样作为validate()方法调用的一部分进行验证。 Is this something to do with this bean being referred to from another bean rather than directly from the method that calls validate() ? 这与从另一个bean而不是直接从调用validate()的方法中引用该bean有关吗?

Thanks 谢谢

You can validate your "entries" field this way: 您可以通过以下方式验证“条目”字段:

@Valid
private EntriesBean entries;

This will make Hibernate validator cascade the validations in that bean 这将使Hibernate验证器在该bean中级联验证

Answered my own question. 回答了我自己的问题。

Reading the very lengthy documentation I can see that the way to do this is to use the pushNestedPath() and popNestedPath() methods of the BindingResult object like so: 阅读冗长的文档,我可以看到,执行此操作的方法是使用BindingResult对象的pushNestedPath()和popNestedPath()方法,如下所示:

    result.pushNestedPath("entries");
    validator.validate(form.getEntries(), result);
    result.popNestedPath();

I don't like this way of doing it as it looks quite messy but it works, it appears 我不喜欢这种方式,因为它看起来很杂乱,但确实有效,

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

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