Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Docs] DTO에 Enum이 존재할때 Validation 하는 방법 #28

Open
sinryuji opened this issue Aug 25, 2023 · 0 comments
Open

[Docs] DTO에 Enum이 존재할때 Validation 하는 방법 #28

sinryuji opened this issue Aug 25, 2023 · 0 comments
Assignees
Labels
documentation Improvements or additions to documentation

Comments

@sinryuji
Copy link
Collaborator

DTO에 Enum Field들을 편하게 Validation 하기 위해 커스텀 어노테이션을 작성해두었습니다.

@Constraint(validatedBy = EnumValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidEnum {

    String message() default "잘못된 Enum 값입니다.";

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

    Class<? extends Payload>[] payload() default {};

    Class<? extends java.lang.Enum<?>> enumClass();
}
@NotNull(message = "팀 타입이 비어있습니다!")
@ValidEnum(enumClass = TeamType.class)
private TeamType type;

위와 같이 DTO의 필드에 @ValidEnum을 붙여주시면 되고 enumClass로 Enum 클래스를 주시면 됩니다.

@Override
public boolean isValid(Enum value, ConstraintValidatorContext context) {
    Object[] enumValues = this.annotation.enumClass().getEnumConstants();
    if (enumValues != null) {
        for (Object enumValue : enumValues) {
            if (value == enumValue) {
                return true;
            }
        }
    }
    return false;
}

ConstraintValidator를 상속한 EnumValidator의 isValid에서 Enum value가 유효한지 확인합니다.

@JsonCreator
public static TeamType from(String value) {
    for (TeamType status : TeamType.values()) {
        if (status.getValue().equals(value)) {
            return status;
        }
    }
    return null;
}

@JsonValue
public String getValue() {
    return value;

추가로 Enum 클래스를 작성하실 때 위와 같이 @JsonCreator와 @JsonValue로 역직렬화를 구현해놓으셔야 Enum Value로 Enum 타입의 변수에 대입이 가능해집니다. @JsonCreator가 존재하지 않으면 DTO로 넘어온 Enum Value로는 Enum 타입의 변수에 대입이 불가능해 타입 에러가 발생합니다.

@sinryuji sinryuji self-assigned this Aug 25, 2023
@sinryuji sinryuji added the documentation Improvements or additions to documentation label Aug 25, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant