[SpringBoot2.4.3] PhoneValidatorクラスの作成

PhoneValidator.java

package com.example.demo;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PhoneValidator implements ConstraintValidator<Phone, String>{
	
	@Override
	public void initialize(Phone phone) {
		
	}
	
	@Override
	public boolean isValid(String input, ConstraintValidatorContext cxt) {
		if(input == null) {
			return false;
		}
		return input.matches("[0-9()-]*");
	}
}

### アノテーションクラス
validation classのためのアノテーションは色々用意しなければならない。

package com.example.demo;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;

@Documented
@Constraint(validatedBy = PhoneValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
public @interface Phone {
	
	String message() default "please input a phone number.";
	
	Class<?>[] groups() default {};
	
	Class<? extends Payload>[] payload() default{};

}

### Phoneバリデータの使用
MyData.java

	@Column(nullable = true)
	@Phone
	private String memo;

html

		<tr>
			<td><label for="memo">メモ</label></td>
			<td><textarea name="memo" th:text="*{memo}" cols="20" rows="5"  th:errorclass="err"></textarea>
			<div th:if="${#fields.hasErrors('memo')}" th:errors="*{memo}" th:errorclass="err">
			</div></td>
		</tr>

おおお、javaだとなんか異様に感動するな

[SpringBoot2.4.3] javax.validationのアノテーション

### javax.validationパッケージ
@Null, @NotNull
@Min, @Max
@DecimalMin, @DecimalMax
@Digits
@Future @Past
@Size
@Pattern

### Hibernate Validatorアノテーション
@NotEmpty
@Length
@Range
@Email
@CreditCardNumber
@EAN

エンティティ

	@Column(length = 50, nullable = false)
	@NotNull(message="空白は不可")
	private String name;
	
	@Column(length = 200, nullable = true)
	@Email(message="メールアドレスのみ")
	private String mail;
	
	@Column(nullable = true)
	@Min(value=0,message="ゼロ以上")
	@Max(value=200,message="200以下")
	private Integer age;

ValidationMessages.properties

org.hibernate.validator.constraints.NotBlank.message = \u7A7A\u767D\u306F\u4E0D\u53EF\u3067\u3059\u3002
org.hibernate.validator.constraints.NotEmpty.message = \u7A7A\u767D\u306F\u4E0D\u53EF\u3067\u3059\u3002
javax.validation.constraints.Max.message = {value}\u3088\u308A\u5C0F\u3055\u304F\u3057\u3066\u4E0B\u3055\u3044\u3002
javax.validation.constraints.Min.message = {value}\u3088\u308A\u5927\u304D\u304F\u3057\u3066\u4E0B\u3055\u3044\u3002
org.hibernate.validator.constraints.Email.message=\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002

[SpringBoot2.4.3] バリデーション

validationを使うために、pom.xmlで定義する

pom.xml

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
		</dependency>
		
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>2.0.1.Final</version>
		</dependency>

MyData.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name="mydata")
public class MyData{
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column
	@NotNull
	private long id;
	
	@Column(length = 50, nullable = false)
	@NotEmpty
	private String name;
	
	@Column(length = 200, nullable = true)
	@Email
	private String mail;
	
	@Column(nullable = true)
	@Min(0)
	@Max(200)
	private Integer age;
//省略

Controller

import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;

@RequestMapping(value="/", method=RequestMethod.GET)
	public ModelAndView index(
			@ModelAttribute("formModel") MyData mydata,
			ModelAndView mav) {
		mav.setViewName("index");
		mav.addObject("msg","this is sample content.");
		mav.addObject("formModel",mydata);
		Iterable<MyData> list = repository.findAll();
		mav.addObject("datalist", list);
		return mav;
	}
	
	@RequestMapping(value="/", method= RequestMethod.POST)
	@Transactional(readOnly=false)
	public ModelAndView form(
			@ModelAttribute("formModel") 
			@Validated MyData mydata,
			BindingResult result,
			ModelAndView mov) {
		ModelAndView res = null;
		if(!result.hasErrors()) {
			repository.saveAndFlush(mydata);
			res = new ModelAndView("redirect:/");
		} else {
			mov.setViewName("index");
			mov.addObject("msg","sorry, error is occured...");
			Iterable<MyData> list = repository.findAll();
			mov.addObject("datalist",list);
			res = mov;
		}
		return res;
	}

html

		<ul>
			<li th:each="error : ${#fields.detailedErrors()}" class="err" th:text="${error.message}">
		</ul>

うおおおおおお、凄え

html

	<table>
		<form method="post" action="/" th:object="${formModel}">
		<tr>
			<td><label for="name">名前</label></td>
			<td><input type="text" name="name" th:value="*{name}" th:errorclass="err">
			<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}" th:errorclass="err">
			</div>
			</td>
		</tr>
		<tr>
			<td><label for="age">年齢</label></td>
			<td><input type="text" name="age" th:value="*{age}"  th:errorclass="err">
			<div th:if="${#fields.hasErrors('age')}" th:errors="*{age}" th:errorclass="err">
			</div></td>
		</tr>
		<tr>
			<td><label for="mail">メール</label></td>
			<td><input type="text" name="mail" th:value="*{mail}"  th:errorclass="err">
			<div th:if="${#fields.hasErrors('mail')}" th:errors="*{mail}" th:errorclass="err">
			</div></td>
		</tr>
		<tr>
			<td><label for="memo">メモ</label></td>
			<td><textarea name="memo" th:text="*{memo}" cols="20" rows="5"></textarea></td>
		</tr>
		<tr>
			<td></td>
			<td><input type="submit"/></td>
		</tr>
		</form>
	</table>

こうもできる