[Java/Spring] Custom Validation

Hyeri Park·2022년 8월 1일
0

JAVA/Spring 기초

목록 보기
13/22
post-thumbnail

Custom Validation ?

  1. AssertTrue/False 와 같은 method 지정을 통해 Custom Logic 적용 가능

  2. ConstraintValidator를 적용하여 재사용이 가능한 Custom Logic 적용 가능

경로

1. 예시

User.java

package com.example.validation.dto;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import com.example.validation.annotation.YearMonth;

public class User {
	
	@NotBlank
	private String name;
	
	@Min(value = 0)
	@Max(value = 90)
	private int age;
	
	@Email
	private String email;
	
	@Pattern(regexp = "^\\d{2,3}-\\d{3,4}-\\d{4}$", message = "핸드폰 번호 양식이 맞지 않습니다.")
	private String phoneNumber;

	// ================ 이 부분 추가 (아래 getter,setter추가) ===============
	@YearMonth(pattern = "yyyyMM") 
	private String reqYearMonth; // YYYY-MM
	// ================ 이 부분 추가 ===============
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}
	
	

	public String getReqYearMonth() {
		return reqYearMonth;
	}

	public void setReqYearMonth(String reqYearMonth) {
		this.reqYearMonth = reqYearMonth;
	}
	
	// ================ 이 부분 추가 ===============
	@AssertTrue(message = "yyyyMM의 형식에 맞춰야합니다.")
	public boolean isReqYearMonthValidation() {
		this.reqYearMonth = getReqYearMonth()+"01";
		
		try {
			LocalDate localDate = LocalDate.parse(this.reqYearMonth, DateTimeFormatter.ofPattern("yyyyMMdd"));
			
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	// ================ 이 부분 추가 ===============
	
	@Override
	public String toString() {
		return "User [name=" + name + ", age=" + age + ", email=" + email + ", phoneNumber=" + phoneNumber
				+ ", reqYearMonth=" + reqYearMonth + "]";
	}

	
	
	


	
}


2. 예시

email, pattern annotation에서 아래와같이 형식을 복붙해온다.

email 클릭

pattern 클릭


YearMonth.java

package com.example.validation.annotation;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

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

import com.example.validation.validator.YearMonthValidator;

@Constraint(validatedBy = {YearMonthValidator.class})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)

public @interface YearMonth {

	String message() default "yyyyMM 형식에 맞지 않습니다.";

	Class<?>[] groups() default { };

	Class<? extends Payload>[] payload() default { };
	
	String pattern() default "yyyyMMdd";
}

YearMonthValidator.java

package com.example.validation.validator;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

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

import com.example.validation.annotation.YearMonth;

public class YearMonthValidator implements ConstraintValidator<YearMonth, String>{

	private String pattern;

	@Override
	public void initialize(YearMonth constraintAnnotation) {
		this.pattern = constraintAnnotation.pattern();
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		
		// yyyyMM01
		System.out.println(this.pattern);
		try {
			LocalDate localDate = LocalDate.parse(value+"01", DateTimeFormatter.ofPattern(this.pattern)); //01은 무조건  디폴트로 01일 지정해주는 의미이다.
			
		} catch (Exception e) {
			return false;
		}
		return true;
		
	}

User.java 수정

@YearMonth
	private String reqYearMonth; // YYYY-MM

profile
Backend Developer

0개의 댓글