love.keeping.starter.web.components.validation.EnumValidator Maven / Gradle / Ivy
The newest version!
package love.keeping.starter.web.components.validation;
import love.keeping.starter.common.utils.ObjectUtil;
import love.keeping.starter.common.utils.StringUtil;
import love.keeping.starter.web.enums.BaseEnum;
import love.keeping.starter.web.utils.EnumUtil;
import java.io.Serializable;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 枚举校验 如果参数是null 则通过校验
*
* @author Keeping
*/
public class EnumValidator implements ConstraintValidator {
private Class extends BaseEnum extends Serializable>> enumsClass;
@Override
public void initialize(IsEnum constraintAnnotation) {
this.enumsClass = constraintAnnotation.enumClass();
}
@Override
public boolean isValid(Serializable value, ConstraintValidatorContext context) {
return ObjectUtil.isNull(value) || ObjectUtil.isNotNull(EnumUtil.getByCode(enumsClass, value))
|| (
value instanceof CharSequence && StringUtil.isEmpty((CharSequence) value));
}
}