0
0

More than 1 year has passed since last update.

Spring Boot フォーム入力のエラーメッセージを簡単に出す

Posted at

はじめに

今回はフォーム入力のエラーメッセージを簡単に実装する方法です。

Entityクラス

今回は書籍投稿アプリのEntityクラスのコードです。

@NotBlank(message = "入力必須です!")
  @Column(name = "title")
  @Size(max = 30)
  private String title;

  @NotBlank(message = "入力必須です!")
  @Column(name = "genre")
  @Size(max = 10)
  private String genre;

  @NotNull(message = "入力必須です!")
  @Column(name = "favorite")
  @Min(0)
  @Max(5)
  private int favorite;

  @NotBlank(message = "入力必須です!")
  @Column(name = "content")
  @Size(max = 500)
  private String content;

  @NotBlank(message = "入力必須です!")
  @Column(name = "publisher")
  private String publisher;

  @NotNull(message = "入力必須です!")
  @Column(name = "price")
  @Min(0)
  private Integer price;

スクリーンショット 2022-12-23 10.46.31.png

このようにSpring Bootのバリデーション機能を実装する、@NotBlank,@NotNull,@Sizeなどのアノテーションを後ろに、message = ""と記述するとmessageに指定した通りのエラーメッセージが表示されます。
@Sizeアノテーションにもつけられます。

@Size(min = 0, max = 20, message = "20文字以内で入力してください!")

以上です。

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