springMVC自定义校验注解

发布时间 2023-10-02 19:20:29作者: 空嘘一场

 

1.定义注解校验器

PhoneNoValidator.java
 1 /**
 2  * @Author hxy
 3  * @Description
 4  * @Date 2023/9/14 10:48
 5  * @Version 1.0
 6  */
 7 public class PhoneNoValidator implements ConstraintValidator<PhoneNo, String> {
 8     @Override
 9     public void initialize(PhoneNo constraintAnnotation) {
10     }
11 
12     @Override
13     public boolean isValid(String phoneNo, ConstraintValidatorContext context) {
14         if (phoneNo == null || phoneNo.isEmpty()){
15             return false;
16         }
17 
18         if (phoneNo.matches("((\\+86)|(86))?1[3|4|5|8]\\d{9}")){
19             return true;
20         }
21         return false;
22     }
23 }

2.定义校验注解

PhoneNo.
interface
 1 import static  java.lang.annotation.ElementType.*;
 2 import static  java.lang.annotation.ElementType.PARAMETER;
 3 import static  java.lang.annotation.RetentionPolicy.RUNTIME;
 4 /**
 5  * @Author hxy
 6  * @Description
 7  * @Date 2023/9/14 10:49
 8  * @Version 1.0
 9  */
10 @Target({METHOD, FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER})
11 @Retention(RUNTIME)
12 @Documented
13 @Constraint(validatedBy =  {PhoneNoValidator.class})
14 public @interface PhoneNo {
15     //错误提示信息
16     String message() default "手机号码格式错误";
17 
18     //分组
19     Class<?>[] groups() default {};
20     //负载
21     Class<? extends Payload>[] payload() default {};
22     //指定多个时使用
23     @Target({METHOD, FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER})
24     @Retention(RUNTIME)
25     @Documented
26     @interface list{
27         PhoneNo[] value();
28     }
29 }