🫣
[Spring]バリテーション
バリテーションとは
フォームなどから送られてくるユーザーからの入力の正しさをチェックする仕組みです。
入力漏れや正しい形式かをチェックしてエラーを防ぎます。
また、ユーザー側にわかりやすいエラーメッセージを返すことができます。
使用方法
フォームクラスにアノテーションを付けます。
public class UserForm {
@NotBlank
private String name;
@Email(message = "正しいメールアドレスを入力してください")
private String email;
@Size(min = 8, message = "パスワードは8文字以上で入力してください")
private String password;
}
バリテーション結果の受け取りは、コントローラーに@Validated
,BindingResult
を付けます。
@PostMapping("/create")
public String createUser(
@Validated UserForm userForm,
BindingResult bindingResult
) {
if (bindingResult.hasErrors()) {
return "registerForm"; // エラーがあればフォームに戻す
}
// エラーがなければ登録処理
return "createdForm";
}
バリテーションエラーの表示はth:errors
を使用します
<form th:action="@{/create}" method="post" th:object="${userForm}">
<label for="title">タイトル</label>
<input type="text" id="title" th:field="*{name}" />
<p th:errors="*{name}"></p>
<label for="email">メールアドレス</label>
<input type="email" id="email" th:field="*{email}" />
<p th:errors="*{email}"></p>
<label for="password">パスワード</label>
<input type="password" id="password" th:field="*{password}" />
<p th:errors="*{password}"></p>
<button type="submit">送信</button>
</form>
バリテーションの例
アノテーション | 意味 |
---|---|
@NotBlank |
null・空文字・空白すべてNG |
@NotNull |
nullだけ禁止(空文字("")、空コレクション([])はOK) |
@NotEmpty |
nullは禁止(文字数が0かどうか) |
@Size |
文字数や配列のサイズ制限(@Size(min=2, max=5) サイズが2以上5以下?) |
@Min , @Max
|
指定した数値の最小以上(Min(3) ), 最大以下であるか(Max(3) ) |
@Email |
メール形式かどうか |
@Pattern(regex=) |
正規表現にマッチするか |
@Past , @Future
|
過去・未来の日付かどうか |
@NotNull
,@NotEmpty
,@NotBlank
の違い
値 | @NotNull |
@NotEmpty |
@NotBlank |
---|---|---|---|
null |
❌ | ❌ | ❌ |
"" |
✅ | ❌ | ❌ |
" " |
✅ | ✅ | ❌ |
"abc" |
✅ | ✅ | ✅ |
Discussion