Spring 中的条件验证
我有一个包含一些单选
按钮和复选框
的表单。每当用户选择/取消选择单选按钮
或复选框
时,就会启用/禁用其他一些输入字段。
我想仅对用户提交表单时启用的字段添加验证。提交时禁用的字段不应考虑进行验证。
我不想在客户端验证中添加这个。在 Spring 3.0 中是否有更好/简单的方法来实现条件验证,而不是在验证器中添加多个 if
?
谢谢!
I have a form which contain some radio
button and check-boxes
. Whenever user selects/deselects a radio button
or check-box
few other input fields are enabled/disabled.
I want to add validation only for fields which are enabled when user submits the form. Fields which are disabled at the time of submission should not be considered for validation.
I don't want to add this in client side validation.Is there any better /easy way to implement conditional validation in Spring 3.0 instead of adding multiple if
in validator ?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 JSR 303 Bean 验证,则可以使用 验证组(
组
)。假设您有此用户输入,其中包含两个部分。
两个布尔值指示这些部分是启用还是禁用。 (当然,您可以使用比
@NotNull
更有用的注释)您需要两个组接口。它们仅用作标记。
自 Spring 3.1 您可以在控制器方法中使用 Spring
@Validated
注解(而不是@Validate
)来触发验证:在 Spring 3.1 之前没有办法指定应该用于验证的验证组(因为
@Validated
不存在且@Validate
没有group属性),所以需要启动验证手工编写代码:这是一个如何根据 Spring 3.0 中启用的女巫部分触发验证的示例。(顺便说一句:对于 Spring 3.0 解决方案,也可以让 Spring 注入验证器:
)
If you use JSR 303 Bean validation then you can use validation groups (
groups
) for this.Assume you have this user input, containing two sections.
The two booleans indicating if the sections are enabled or disabled. (Of course you can use more useful annotations than
@NotNull
)You need two Interfaces for the groups. They work only as marker.
Since Spring 3.1 you can use the Spring
@Validated
annotation (instead of@Validate
) in your controller method to trigger the validation:Before Spring 3.1 there was no way to specify the validation group that should been used for validation (because
@Validated
does not exist and@Validate
does not have a group attribute), so you need to start the validation by hand written code: This an an example how to trigger the validation in dependence to witch section is enabled in Spring 3.0.(BTW: For the Spring 3.0 solution, it is also possible to let Spring inject the validator:
)
当字段被禁用时,它们将作为
null
传输到控制器。我想添加一个验证,允许null
(即禁用字段)或not Blank
字段(即启用但为空字段)。因此,我创建了一个自定义注释
NotBlankOrNull
,它将允许null
和非空字符串,并且它还可以处理空格。这是我的注释
验证器类,
我还在我的 网站上更新了更多详细信息。
When fields are disabled they are transferred to controller as
null
. I wanted to add a validation which will allow eithernull
i.e disabled field ornot blank
field i.e. enabled but empty field.So I created a custom annotation
NotBlankOrNull
which will allownull
and non empty strings also it takes care of blank spaces.Here is my Annotation
Validator class
I have also updated more details on my site.