2017-08-04 56 views
0

我有我的自定義validator,我想爲它添加一些錯誤消息。 所以我有下面的代碼:是否可以爲約束違反模板消息添加消息參數?

@Override 
public boolean isValid(final String label, 
         final ConstraintValidatorContext constraintValidatorContext) { 
    constraintValidatorContext.disableDefaultConstraintViolation(); 

    if(label.length() > MAX_LENGTH) { 
      constraintValidatorContext 
        .buildConstraintViolationWithTemplate("{error.maxLength}") 
        .addConstraintViolation(); 
      return false; 
    } 
    ... 
} 

我的消息看起來像error.maxLength=You have exceeded max length of {0},因此具有maxLength參數。

建築約束違規時可以添加它嗎?

回答

3

是的,你可以。

你必須解開的ConstraintValidatorContextHibernateConstraintValidatorContext有:

HibernateConstraintValidatorContext hibernateConstraintValidatorContext = constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class); 

然後,您可以使用:

hibernateConstraintValidatorContext.addMessageParameter("name", value); 

(和你看起來像一個消息參數({variable}),所以它可能是你必須使用 - 注意你需要HV 5.4.1.Final有這種方法)

hibernateConstraintValidatorContext.addExpressionVariable("name", value); 

,如果它是(因此使用表達式語言和類似${variable}

+0

感謝表達變量,已經發現了它。 –