| | |
| | | package com.iailab.framework.common.validation; |
| | | |
| | | import com.iailab.framework.common.core.IntArrayValuable; |
| | | import com.iailab.framework.common.core.ArrayValuable; |
| | | |
| | | import javax.validation.ConstraintValidator; |
| | | import javax.validation.ConstraintValidatorContext; |
| | | import java.util.Arrays; |
| | | import java.util.Collections; |
| | | import java.util.List; |
| | | import java.util.stream.Collectors; |
| | | |
| | | public class InEnumValidator implements ConstraintValidator<InEnum, Integer> { |
| | | public class InEnumValidator implements ConstraintValidator<InEnum, Object> { |
| | | |
| | | private List<Integer> values; |
| | | private List<?> values; |
| | | |
| | | @Override |
| | | public void initialize(InEnum annotation) { |
| | | IntArrayValuable[] values = annotation.value().getEnumConstants(); |
| | | ArrayValuable<?>[] values = annotation.value().getEnumConstants(); |
| | | if (values.length == 0) { |
| | | this.values = Collections.emptyList(); |
| | | } else { |
| | | this.values = Arrays.stream(values[0].array()).boxed().collect(Collectors.toList()); |
| | | this.values = Arrays.asList(values[0].array()); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public boolean isValid(Integer value, ConstraintValidatorContext context) { |
| | | public boolean isValid(Object value, ConstraintValidatorContext context) { |
| | | // 为空时,默认不校验,即认为通过 |
| | | if (value == null) { |
| | | return true; |
| | |
| | | if (values.contains(value)) { |
| | | return true; |
| | | } |
| | | // 校验不通过,自定义提示语句(因为,注解上的 value 是枚举类,无法获得枚举类的实际值) |
| | | // 校验不通过,自定义提示语句 |
| | | context.disableDefaultConstraintViolation(); // 禁用默认的 message 的值 |
| | | context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate() |
| | | .replaceAll("\\{value}", values.toString())).addConstraintViolation(); // 重新添加错误提示语句 |