/**
* <p>枚举校验器</p>
*/
public class EnumObjectValidator implements ConstraintValidator<EnumObjectValid, Integer> {
private Class<? extends Enum> enumClass;
private boolean required;
@Override
public void initialize(EnumObjectValid constraintAnnotation) {
enumClass = constraintAnnotation.enumClass();
required = constraintAnnotation.required();
}
/**
* <p>校验code是否属于枚举值</p>
*
* @param code
* @param constraintValidatorContext
* @return
* @throws
* @author hongtao.su
* @date 2023/7/18 15:45
*/
@Override
public boolean isValid(Integer code, ConstraintValidatorContext constraintValidatorContext) {
if (!required && code == null) {
return true;
}
if (code == null) {
return false;
}
EnumConstraint[] enums = (EnumConstraint[]) enumClass.getEnumConstants();
if (enums == null || enums.length == 0) {
return false;
}
return enums[0].exist(code);
}
}
/**
* <p>枚举校验</p>
*/
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {EnumObjectValidator.class})
@Documented
public @interface EnumObjectValid {
boolean required() default true;
String message() default "enum.is.invalid";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
Class<?>[] target() default {};
Class<? extends Enum<?>> enumClass();
}
提供一个枚举校验类以及校验注解,用户校验接口入参枚举值的合法性
eg:
@Data
public class AuditVehicleConfDTO {
@NotNull(message = "状态不可以为空")
@EnumObjectValid(message = "状态不合法", enumClass = StatusEnum.class)
private Integer auditStatus;
}