Commit 6a7be19d3a401f5138d899570c79c5e5ec708849
1 parent
c25bf38f
common: 增加InEnumCollectionValidator,用于校验枚举值列表参数的取值范围是否有䇅
Showing
2 changed files
with
43 additions
and
1 deletions
yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/validation/InEnum.java
| ... | ... | @@ -17,7 +17,7 @@ import java.lang.annotation.*; |
| 17 | 17 | @Retention(RetentionPolicy.RUNTIME) |
| 18 | 18 | @Documented |
| 19 | 19 | @Constraint( |
| 20 | - validatedBy = InEnumValidator.class | |
| 20 | + validatedBy = {InEnumValidator.class, InEnumCollectionValidator.class} | |
| 21 | 21 | ) |
| 22 | 22 | public @interface InEnum { |
| 23 | 23 | ... | ... |
yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/validation/InEnumCollectionValidator.java
0 → 100644
| 1 | +package cn.iocoder.yudao.framework.common.validation; | |
| 2 | + | |
| 3 | +import cn.hutool.core.collection.CollUtil; | |
| 4 | +import cn.iocoder.yudao.framework.common.core.IntArrayValuable; | |
| 5 | + | |
| 6 | +import javax.validation.ConstraintValidator; | |
| 7 | +import javax.validation.ConstraintValidatorContext; | |
| 8 | +import java.util.Arrays; | |
| 9 | +import java.util.Collection; | |
| 10 | +import java.util.Collections; | |
| 11 | +import java.util.List; | |
| 12 | +import java.util.stream.Collectors; | |
| 13 | + | |
| 14 | +public class InEnumCollectionValidator implements ConstraintValidator<InEnum, Collection<Integer>> { | |
| 15 | + | |
| 16 | + private List<Integer> values; | |
| 17 | + | |
| 18 | + @Override | |
| 19 | + public void initialize(InEnum annotation) { | |
| 20 | + IntArrayValuable[] values = annotation.value().getEnumConstants(); | |
| 21 | + if (values.length == 0) { | |
| 22 | + this.values = Collections.emptyList(); | |
| 23 | + } else { | |
| 24 | + this.values = Arrays.stream(values[0].array()).boxed().collect(Collectors.toList()); | |
| 25 | + } | |
| 26 | + } | |
| 27 | + | |
| 28 | + @Override | |
| 29 | + public boolean isValid(Collection<Integer> list, ConstraintValidatorContext context) { | |
| 30 | + // 校验通过 | |
| 31 | + if (CollUtil.containsAll(values, list)) { | |
| 32 | + return true; | |
| 33 | + } | |
| 34 | + // 校验不通过,自定义提示语句(因为,注解上的 value 是枚举类,无法获得枚举类的实际值) | |
| 35 | + context.disableDefaultConstraintViolation(); // 禁用默认的 message 的值 | |
| 36 | + context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate() | |
| 37 | + .replaceAll("\\{value}", CollUtil.join(list, ","))).addConstraintViolation(); // 重新添加错误提示语句 | |
| 38 | + return false; | |
| 39 | + } | |
| 40 | + | |
| 41 | +} | |
| 42 | + | ... | ... |