spring 表单错误标签:检查特定错误(例如,仅在不存在 not null 时显示无效)

发布于 2024-12-28 12:38:54 字数 142 浏览 1 评论 0原文

因此,我有一个字符串,我需要检查我使用模式的有效格式,以及根据我使用自定义验证器的某些业务规则输入的值是否有效。现在,如果只有在前者没有发生的情况下才显示与后者相关的错误消息,那么客户会更喜欢它。但据我所知,没有办法做出这种区分。 或者有人能想出一种方法来做到这一点吗?

So I have a String I need to check for a valid format for which I used a pattern, and whether the entered value is valid according to some business rules for which I used a custom validator. Now the customer would prefer it if the error message associated with the latter is only shown if the former didn't occur. But as far as I know there is no way to make this distinction.
Or can anyone think of a way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冰雪之触 2025-01-04 12:38:54

技巧是:有两个不同的约束(注释),

  • 一个用于模式,接受 null,
  • 第二个用于非 null。

默认情况下,javax.validation.constraints.Pattern“验证器”接受 null。

接受字符串。 null 元素被视为有效。
(javax.validation.constraints.Pattern javadoc)

所以你最终需要做的是:

@NotNull(message="{validation.notNull}")
@Pattern(pattern="123" message="{validation.notPattern}")
String myString;

添加:

(评论)

这并不是真正想要的行为,因为我想重用 bean 对象,但每个页面的条件并不相同。 – 杰克·尼克尔斯 5 分钟前

在这种情况下,您可以使用所谓的(请参阅JSR303 Bean 验证规范,第 4.1.2 章组 -- 还有一个例子)。对 @Pattern 使用默认组,对 @NotNull 使用其他组。现在,您可以根据指定用于验证的组启用或禁用验证规则。

validator.validate(myObject, Default.class);
validator.validate(myObject, MyGroup.class);

还剩下一个问题:在 Spring 3.0 中,您无法指定要用于自动验证过程的组。但在 3.1 中,您可以根据该功能请求 SPR-6373 (我没有尝试过它,但我希望它有效)

The trick is: have two different constraints (annotations),

  • one for the pattern, that accept null,
  • and a second for not null.

By default the javax.validation.constraints.Pattern "validator" accept null.

Accepts String. null elements are considered valid.
(javax.validation.constraints.Pattern javadoc)

So what you need to do in the end is this:

@NotNull(message="{validation.notNull}")
@Pattern(pattern="123" message="{validation.notPattern}")
String myString;

Added:

(Comment)

Not really the desired behaviour since I want to reuse the bean object but the conditions aren't the same for each page. – Jack Nickels 5 mins ago

In this case you can use the so called groups (See JSR303 Bean Validation Spec, Chapter 4.1.2 groups -- there is also an example). Use the default Group for @Pattern and an other group for @NotNull. Now you can enable or disable the Validation rules according the groups you specify for validation.

validator.validate(myObject, Default.class);
validator.validate(myObject, MyGroup.class);

There is one problem left: in Spring 3.0 you can not Specify the Group you want to use for the automatic validation process. But in 3.1 you can, according to that Feature Request SPR-6373 (I have not tryed it, but I hope it works)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文