hibernate验证器:验证2个字段匹配

发布于 2024-10-06 19:48:47 字数 82 浏览 2 评论 0原文

我想知道,我是否忽略了某些内容,或者休眠验证器是否没有提供注释来验证两个字段是否相等(例如密码)。 我知道我可以编写自己的验证器,但这似乎是标准功能。

I was wondering, am I overlooking something or does the hibernate validator offer no annotation to verify that 2 fields are equal (such as a password).
I know I can write my own validators, but well this seems like standard functionality.

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

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

发布评论

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

评论(4

逐鹿 2024-10-13 19:48:47

如果您使用 Spring 框架,那么您可以使用 Spring 表达式语言 (SpEL)。我编写了一个小型库,它提供基于 SpEL 的 JSR-303 验证器,使跨领域验证变得非常容易。看看 https://github.com/jirutka/validator-spring

当至少其中一个不为空时,这将验证密码字段的相等性。

@SpELAssert(value = "password.equals(passwordVerify)",
            applyIf = "password || passwordVerify",
            message = "{validator.passwords_not_same}")
public class User {

    private String password;
    private String passwordVerify;
}

If you’re using Spring Framework then you can use Spring Expression Language (SpEL) for that. I’ve wrote small library that provides JSR-303 validator based on SpEL that makes cross-field validations very easy. Take a look at https://github.com/jirutka/validator-spring.

This will validate equality of password fields when at least one of them is not empty.

@SpELAssert(value = "password.equals(passwordVerify)",
            applyIf = "password || passwordVerify",
            message = "{validator.passwords_not_same}")
public class User {

    private String password;
    private String passwordVerify;
}
感悟人生的甜 2024-10-13 19:48:47

只是选择了自定义验证器路线。这里的其他两个答案与这个问题并不真正相关。
通过一些谷歌搜索,我找到了一个字段匹配的例子。

Just went for the custom validator route. The other 2 answers here aren't really related to the question.
With a bit of googling I found a fieldmatch example.

巷雨优美回忆 2024-10-13 19:48:47

Hibernate 是一个 ORM 映射器。

它用于将数据保存到数据库中并再次提取。因此,拥有两个具有相同值的字段没有多大意义(从持久性的角度来看)。这是您应该在业务逻辑中检查的内容。

我同意 Junesh...不要以可检索的格式保留您的密码...查找 Hasing 和 Salting - 或者更好的是,考虑 openID,这样您就不必用另一个愚蠢的密码来打扰您的客户...

Hibernate is a ORM Mapper.

It is used to persist data into a DB and extract it again. As such, having 2 fields with an identical value makes not much sense (From a persistance point of view). Thats something you should check in your Business logic.

And I am with Junesh... Dont persist your passwords in a retrievable format... Look up Hasing and Salting - Or even better, think about openID so you dont have to bother your clients with yet another stupid password...

但可醉心 2024-10-13 19:48:47

我希望您也没有将确认密码保存在数据库中。您没有任何现成的验证,但您必须使用自定义注释,这也非常简单。

I am hoping you are not saving the confirm password in the database as well. You do not have any out of the box validations for this, but instead you will have to use custom annotation which is pretty straight forward as well.

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