Building Dynamic ConstraintViolation Error Messages

后端 未结 2 757
囚心锁ツ
囚心锁ツ 2021-02-06 03:02

I\'ve written a validation annotation implemented by a custom ConstraintValidator. I also want to generate very specific ConstraintViolation objects th

相关标签:
2条回答
  • 2021-02-06 03:17

    If you use message codes you can simply add something like {0} in them.

    For example: "The field {0} must not be empty."

    And then use hibernateContext.addMessageParameter("0", fieldName); instead of addExpressionVariable(...).

    That worked for me.

    0 讨论(0)
  • 2021-02-06 03:26

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

    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;
        }
    }
    

    The reference guide has some more details.

    0 讨论(0)
提交回复
热议问题