1、定义性别枚举
1.1 BaseEnum.java
package com.jingai.validation.custom;
public interface BaseEnum {
String getCode();
String getDisplay();
}
1.2 GenderEnum.java
package com.jingai.validation.custom;
public enum GenderEnum implements BaseEnum {
male("1", "男"),
female("0", "女");
private String code;
private String display;
private GenderEnum(String code, String display) {
this.code = code;
this.display = display;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDisplay() {
return this.display;
}
}
2 、自定义枚举类型的校验规则
package com.jingai.validation.custom;
import org.springframework.util.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 验证给定的String值是否满足InEnum注解中的约束
*/
public class InEnumValidator implements ConstraintValidator<InEnum, String> {
private Class<? extends BaseEnum> enumType;
/**
* 初始化方法可以获得该校验器对应的注解,从而获取注解中的信息。在校验方法调用前会调用
*/
@Override
public void initialize(InEnum constraintAnnotation) {
enumType = constraintAnnotation.enumType();
}
/**
* 校验。成功返回true,失败返回false
*/
@Override
public boolean isValid(String str, ConstraintValidatorContext constraintValidatorContext) {
if(!StringUtils.hasText(str)) {
return true;
}
if(enumType == null || !enumType.isEnum()) {
return false;
}
for (BaseEnum e :enumType.getEnumConstants()){
if(e.getCode().equals(str)) {
return true;
}
}
return false;
}
}
3、自定义校验规则注解
package com.jingai.validation.custom;
import javax.validation.Constraint;
import javax.validation.Payload;
impo