Building Dynamic ConstraintViolation Error Messages

后端 未结 2 788
囚心锁ツ
囚心锁ツ 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: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 {
    
        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.

提交回复
热议问题