建立动态ConstraintViolation错误消息 [英] Building Dynamic ConstraintViolation Error Messages

查看:66
本文介绍了建立动态ConstraintViolation错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个由自定义 ConstraintValidator 实现的验证注释.我还想生成非常具体的 ConstraintViolation 对象,这些对象使用在消息插值期间的验证过程中计算出的值.

I've written a validation annotation implemented by a custom ConstraintValidator. I also want to generate very specific ConstraintViolation objects that use values computed during the validation process during message interpolation.

public class CustomValidator 
  implements ConstraintValidator<CustomAnnotation, ValidatedType> {

...
  @Override
  public boolean isValid(ValidatedType value, ConstraintValidatorContext context) {
    // Figure out that the value is not valid.
    // Now, I want to add a violation whose error message requires arguments.
  }
}

我的消息源中的假设错误消息:

A hypothetical error message in my message source:

CustomAnnotation.notValid = The supplied value {value} was not valid because {reason}.

传递给 isValid 方法的上下文提供了一个用于建立约束违例并将其最终添加到上下文中的接口.但是,我似乎无法弄清楚如何使用它.根据此文档

The context passed into the isValid method provides an interface for building up a constraint violation, and finally adding it to the context. However, I can't seem to figure out how to use it. According to this documention for the version I'm using, I can add bean and property nodes to the violation. These are the only additional details I can specify to the violation definition, but I don't understand how they might map to parameters in the error message.

数百万美元的问题:如何使用自定义验证程序将动态参数传递给我的验证错误消息?我想填写那些 {value} 字段,使用 ConstraintValidatorContext 的界面来构建违规行为.

Million dollar question: how can I pass dynamic parameters to my validation error messages using a custom validator? I would like to fill in those {value} and {reason} fields using the ConstraintValidatorContext's interface for building violations.

获取消息源的实例并在自定义验证器中对消息进行插值不是一种选择-无论如何,都会对来自验证的消息进行插值,并且在内部插值将导致某些消息被插值两次,从而可能消灭转义的消息我的邮件定义文件中的单引号或其他具有特殊含义的字符.

Obtaining an instance of the message source and interpolating the message within the custom validator is not an option - the messages coming out of validation get interpolated no matter what, and interpolating internally will result in some messages being interpolated twice, potentially annihilating escaped single quotes or other characters with special meanings in my message definitions file.

推荐答案

标准化的Bean Valiation API无法实现,但是BV参考实现Hibernate Validator中有一种方法.

That's not possible with the standardized Bean Valiation API, but there is a way in Hibernate Validator, the BV reference implementation.

您需要将 ConstraintValidatorContext 展开为 HibernateConstraintValidatorContext ,这使您可以访问 addExpressionVariable()方法:

You need to unwrap the ConstraintValidatorContext into a HibernateConstraintValidatorContext which gives you access to the addExpressionVariable() method:

public class MyFutureValidator implements ConstraintValidator<Future, Date> {

    public void initialize(Future constraintAnnotation) {}

    public boolean isValid(Date value, ConstraintValidatorContext context) {
        Date now = GregorianCalendar.getInstance().getTime();

        if ( value.before( now ) ) {
            HibernateConstraintValidatorContext hibernateContext =
                context.unwrap( HibernateConstraintValidatorContext.class );

            hibernateContext.disableDefaultConstraintViolation();
            hibernateContext.addExpressionVariable( "now", now )
                .buildConstraintViolationWithTemplate( "Must be after ${now}" )
                .addConstraintViolation();

            return false;
        }

        return true;
    }
}

参考指南具有更多详细信息.

这篇关于建立动态ConstraintViolation错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆