提交 | 用户 | 时间
e7c126 1 package com.iailab.framework.common.validation;
H 2
3 import cn.hutool.core.collection.CollUtil;
4 import com.iailab.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