##TelValid
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Constraint(validatedBy = TelValidValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TelValid {
String message() default "000-0000-0000 형식이 아닙니다.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String regexp() default "^\\d{3}-\\d{3,4}-\\d{4}$";
}
##TelValidValidator
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;
public class TelValidValidator implements ConstraintValidator<TelValid, String> {
private String pattern;
@Override
public void initialize(TelValid constraintAnnotation) {
pattern = constraintAnnotation.regexp();
}
@Override
public boolean isValid(String string,
ConstraintValidatorContext constraintValidatorContext) {
//String pattern = "^\\d{4}/\\d{2}/\\d{2}$";
return Pattern.matches(pattern, string);
}
}
##UserDto
import com.example.validation.annotation.DateValid;
import com.example.validation.annotation.TelValid;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.*;
public class UserDto {
@NotBlank
private String name;
@Max(value = 100)
private int age;
@Email
private String email;
//2024/12/03
@JsonProperty(value = "req_year_month_day")
@Size(min = 10, message = "10자리 입니다.")
@DateValid
private String reqYearMonthDay;
@JsonProperty(value = "tel_num")
@Size(min = 13)
@TelValid
private String tel;
// @AssertTrue(message = "yyyy/mm/dd 형식이 아닙니다.")
// public boolean isReqYearMonthDayValidation(){
// String pattern = "^\\d{4}/\\d{2}/\\d{2}$";
// return Pattern.matches(pattern, this.reqYearMonthDay);
// }
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;
}
@Override
public String toString() {
return "UserDto{" +
"name='" + name + '\'' +
", age=" + age +
", email='" + email + '\'' +
'}';
}
}