LoginSignup
6
9

More than 5 years have passed since last update.

SpringのBean Validationでエラーメッセージを動的に切り替える。

Posted at

カスタムバリデーターで、エラーメッセージを動的に切り替えたい場合があります。

たとえば、入力できる漢字をJIS第二水準までに限定するバリデーターを作ったとして、
第三水準の漢字が入力された場合に、エラーメッセージを表示するとします。

その際、エラーメッセージを
『使用できない漢字が含まれています』
ではなく
『「××(←ユーザーが入力した第三水準の漢字)」は使用できない漢字です』
と表示したい、という要望があるかもしれません。

その場合、以下の方法を使えば実現できます。(ConstraintValidatorを実装するカスタムバリデータの場合)


    @Override
    public boolean isValid(String args, ConstraintValidatorContext context) {

        String illegalCharacters = getDifficultKanji(args);//←メソッドは、使えない漢字を戻り値にする

        if(illegalCharacters != null){
            //使えない漢字が検出された場合
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("「" + illegalCharacters + "」は使用できない漢字です")
                .addConstraintViolation();
            return false;

        }
        return true;
    }

以上です。

6
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
9