LoginSignup
2
1

More than 5 years have passed since last update.

カスタムBean ValidatiorでpropertyPathにインデックスを付与する

Last updated at Posted at 2016-04-16

1.やりたいこと

  • Bean Validationでカスタムバリデータを作成してバリデーションをする
  • 対象はコレクション(ArrayやList、Setなど)
  • ConstraintViolation.getPropertyPath()でproperty[1]みたいに取得できたい

2. やったこと

カスタムバリデータで以下のようにViolationの設定をするとよいっぽい。

// ConstraintValidatorContext context
context.buildConstraintViolationWithTemplate(message)
       .addBeanNode()
       .inIterable()
       .atIndex(index)
       .addConstraintViolation()
       .disableDefaultConstraintViolation();

.inIterable()でLeafNodeContextBuilderが取得できるので、
それに対してatIndex(index)を呼び出してIndexを設定する。
ConstraintViolation.getPropertyPath()は、property[1]のようになる。

できた。

ちなみに、LeafNodeContextBuilder#atKey(Object)を呼び出すと

.atKey("xyz") // => property[xyz]

みたいになった。

おわり。

追記

List<Bean>みたいにして、Beanのプロパティにアノテーション付けたら、
こんなことしなくて良い..>_<..

2
1
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
2
1