LoginSignup
0
0

More than 1 year has passed since last update.

SpringBoot Bean Validation:フィールド名を出力する

Last updated at Posted at 2022-01-10

はじめに

Bean Validationのエラーメッセージにフィールド名を出力させるために、プロパティファイルに {0} を追記したが、「{0}を入力してください。」と表示される。
message.propertiesに記述していたのをValidationMessages.propertiesに変えてみたり、@Valid@Validatedに変えたりしたのだが、改善せず。
当たり前に使っていたのに、いざ上手くいかないと、何が原因なのか検討がつかず。解決するまでに、結構は時間を使った・・・。

どうようにお困りの方もいるかと思い記録しておきます。

不足していたのはMessageSourceの利用

bindingResultに登録された時点で、{0}にフィールド名が置き換わると思い込んでいたが、MessageSourceを使って置き換える必要がありました。(フォームだと自動的にやってくれていたのかも?)

Controller(抜粋)

import org.springframework.context.MessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("sample/api")
public SampleController {

  @Autowired
  private MessageSource messageSource;

  SampleResponse index(@Validated @RequestBody SampleRequest request, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
      bindingResult.getAllErrors().stream()
        .map(m -> messageSource.getMessage(m, Locale.getDefault()))
        .forEash(System.out::println);
    }
    return new SampleResponse();
  }
}

ValidationMessages.properties

javax.validation.constraints.NotNull.message={0}を入力してください

messages.properties

name=名前

References

0
0
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
0
0