提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.framework.common.validation; |
H |
2 |
|
|
3 |
import com.iailab.framework.common.core.IntArrayValuable; |
|
4 |
|
|
5 |
import javax.validation.ConstraintValidator; |
|
6 |
import javax.validation.ConstraintValidatorContext; |
|
7 |
import java.util.Arrays; |
|
8 |
import java.util.Collections; |
|
9 |
import java.util.List; |
|
10 |
import java.util.stream.Collectors; |
|
11 |
|
|
12 |
public class InEnumValidator implements ConstraintValidator<InEnum, Integer> { |
|
13 |
|
|
14 |
private List<Integer> values; |
|
15 |
|
|
16 |
@Override |
|
17 |
public void initialize(InEnum annotation) { |
|
18 |
IntArrayValuable[] values = annotation.value().getEnumConstants(); |
|
19 |
if (values.length == 0) { |
|
20 |
this.values = Collections.emptyList(); |
|
21 |
} else { |
|
22 |
this.values = Arrays.stream(values[0].array()).boxed().collect(Collectors.toList()); |
|
23 |
} |
|
24 |
} |
|
25 |
|
|
26 |
@Override |
|
27 |
public boolean isValid(Integer value, ConstraintValidatorContext context) { |
|
28 |
// 为空时,默认不校验,即认为通过 |
|
29 |
if (value == null) { |
|
30 |
return true; |
|
31 |
} |
|
32 |
// 校验通过 |
|
33 |
if (values.contains(value)) { |
|
34 |
return true; |
|
35 |
} |
|
36 |
// 校验不通过,自定义提示语句(因为,注解上的 value 是枚举类,无法获得枚举类的实际值) |
|
37 |
context.disableDefaultConstraintViolation(); // 禁用默认的 message 的值 |
|
38 |
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate() |
|
39 |
.replaceAll("\\{value}", values.toString())).addConstraintViolation(); // 重新添加错误提示语句 |
|
40 |
return false; |
|
41 |
} |
|
42 |
|
|
43 |
} |
|
44 |
|