はじめに
今回はフォーム入力のエラーメッセージを簡単に実装する方法です。
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;
このようにSpring Bootのバリデーション機能を実装する、@NotBlank,@NotNull,@Sizeなどのアノテーションを後ろに、message = ""と記述するとmessageに指定した通りのエラーメッセージが表示されます。
@Sizeアノテーションにもつけられます。
@Size(min = 0, max = 20, message = "20文字以内で入力してください!")
以上です。