2013-07-20 39 views
0

有沒有辦法讓驗證器在驗證失敗時指定消息?我知道我可以實現註解,所以我可以這樣使用它(可能會使用枚舉而不是字符串value,在實踐中):自定義Bean驗證器 - JSR303/JSR349可否驗證器選擇無效時的消息?

@Check(value="Type1", message="{type1.checkFailed}") public MyClass myVal1; 
@Check(value="Type2", message="{type2.checkFailed}") public MyClass myVal2; 

這將得到最終的結果我想要的。我還可以實現多個批註/驗證,並做這種方式並在註釋中的定義指定一個默認的消息:

@CheckType1 public MyClass myVal1; // default message is type1.checkFailed 
@CheckType2 public MyClass myVal2; // default message is type2.checkFailed 

我希望做的是讓與@Check相關的驗證確定是否使用type1.checkFailedtype2.checkFailed的消息,這取決於value,像這樣:

@Check("Type1") public MyClass myVal1; 
@Check("Type2") public MyClass myVal2; 

這是我的理解是,最好的做法是保持專注於單一特性的驗證。但我不認爲我想要做的是與此相反,因爲它是對單一特徵的驗證,它只是可以驗證的變體。

作爲一個例子使用的犬種:

@BreedSize("Large") Dog bigDog; 
@BreedSize("Small") Dog smallDog; 

由於給定的註釋可以僅一個元素(至少SE7的)上出現一次,這也可能是,以確保只有幾個一個合理的方式互相排斥的驗證發生。我認爲/有一個提案在同一個元素上有多個相同類型的註解,但是我認爲驗證者可以檢查只提供了一個,在這種情況下 - 在這裏領先。

這可能嗎?

回答

0

您可以通過ConstraintValidatorContext傳遞給isValid()方法這樣創建自定義的約束衝突對象:

public class BreedSizeValidator implements ConstraintValidator<BreedSize, Dog> { 

    private String value; 

    @Override 
    public void initialize(BreedSize constraintAnnotation) { 
     this.value = constraintAnnotation.value(); 
    } 

    @Override 
    public boolean isValid(
     Dog object, 
     ConstraintValidatorContext constraintContext) { 

     if (object == null) { 
      return true; 
     } 

     boolean isValid = ...; 

     if (!isValid) { 
      String messageKey = "Large".equals(value) ? 
       "{BreedSize.Large.message}" : "{BreedSize.Small.message}"; 

      constraintContext.disableDefaultConstraintViolation(); 
      constraintContext 
       .buildConstraintViolationWithTemplate(messageKey) 
       .addConstraintViolation(); 
     } 

     return isValid; 
    } 
} 
+0

偉大的作品!謝謝。 – CraftWeaver