【问题标题】:How to use placeholders with @Email hibernate validator如何在 @Email 休眠验证器中使用占位符
【发布时间】:2012-01-28 23:56:50
【问题描述】:

默认情况下org.hibernate.validator.constraints.Email 显示not a well-formed email address,但如果用户只输入foo 需要格式良好的电子邮件,我想显示foo is not a well-formed email address。所以我需要有一个foo 的占位符。我的域对象中的属性用@Email 注释。

我的资源包文件中有Email = {0} is not a well-formed email address,当用户在电子邮件字段中输入foo 时,它会显示email is not a well-formed email address

是否可以生成输入的值并将其显示在错误消息中?

我正在使用带有 Spring MVC 3 的 Hibernate 3.5。

谢谢。

【问题讨论】:

    标签: spring-mvc validation hibernate-validator


    【解决方案1】:

    如果您使用 Hibernate Validator 作为您的 Bean Validation Provider,您可以使用 4.2 版中引入的ValueFormatterMessageInterpolator。为此,只需在检索您的 Validator 时设置该插值器,例如像这样:

    Configuration<?> configuration = Validation.byDefaultProvider().configure();
    
    Validator validator = configuration
        .messageInterpolator(new ValueFormatterMessageInterpolator(
            configuration.getDefaultMessageInterpolator()))
        .buildValidatorFactory()
        .getValidator();
    

    使用该插值器,您可以通过错误消息中的占位符 {validatedValue} 引用验证值:{validatedValue} is not a well-formed email address

    您可以在 HV reference guide 中找到更多信息。

    【讨论】:

    • @Gunner:我使用的是 Hibernate 3.5。在 Hibernate 3.5 中不能实现同样的效果吗?我在private String email; 中使用了@Email 来验证该字段。谢谢回复。我会调查的。
    • 那么在您的情况下如何触发验证?在 JPA 2 定义的持久实体上自动执行?在这种情况下,默认验证器工厂用于获取可以使用文件META-INF/validation.xml 配置的验证器。有关示例,请参阅 Hibernate Validator reference guide,该示例还显示了如何设置特定的消息插值器,例如 ValueFormatterMessageInterpolator
    • @Gunner:是的,在持久化实体时会触发验证。
    • 然后应该如上所述使用META-INF/validation.xml 配置插值器就可以了。
    • @Gunner:我一定会这样做的。只是我不是 Hibernate Pro,我可能需要一些时间才能做到这一点,而且我已经让自己处于另一项任务的中间。所以现在我让事情变得简单,并设置了一个静态的“这不是一封格式正确的电子邮件”错误消息。一旦我这样做,我会发布我的答案。非常感谢您的指导:)
    猜你喜欢
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多