自定义注解-手机号验证注解

注解

java 复制代码
package com.XX.assess.annotation;

import com.XX.assess.util.MobileValidator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * 手机号校验注解
 * @author super
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Documented
// 校验规则
@Constraint(validatedBy = MobileValidator.class)
public @interface Mobile {

    boolean required() default true;

    //信息,抛出的是BindException,前端页面接收的话,我们要进行异常的捕获
    String message() default "手机号码格式错误";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

校验规则

java 复制代码
package com.XX.assess.util;

import cn.hutool.core.util.StrUtil;
import com.XX.assess.annotation.Mobile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 自定义校验规则
 * @author super
 */
public class MobileValidator implements ConstraintValidator<Mobile,String> {

    /**
     * 是否必填,默认不必填
     */
    private boolean required = false;

    /**
     * 初始化,获取是否必填
     * @param constraintAnnotation
     */
    @Override
    public void initialize(Mobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    /**
     * 判断是否校验手机号
     * @param value
     * @param context
     * @return
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 必填,则去校验手机号格式
        if (required){
            return ValidatorUtil.Mobile(value);
        }else {
            // 如果不必填,手机号为空,返回ture
            if (StrUtil.isEmpty(value)){
                return true;
            }else {
                // 否则校验手机号格式
                return ValidatorUtil.Mobile(value);
            }
        }
    }
}

校验方法

java 复制代码
package com.XX.assess.util;

import cn.hutool.core.util.StrUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 校验工具类
 */
public class ValidatorUtil {

    private static final Pattern mobile_pattern = Pattern.compile("[1]([3-9])[0-9]{9}$");

    public static boolean Mobile(String mobile) {
        if (StrUtil.isEmpty(mobile)){
            return false;
        }
        Matcher matcher = mobile_pattern.matcher(mobile);
        return matcher.matches();
    }
}
相关推荐
编程、小哥哥29 分钟前
Java面试实战:从Spring Boot到分布式缓存的深度探索
java·spring boot·redis·微服务·grpc·缓存技术·面试技巧
在未来等你30 分钟前
互联网大厂Java求职面试:Spring AI与大模型交互的高级模式与自定义开发
java·微服务·云原生·大模型·spring ai
androidwork37 分钟前
Android Kotlin权限管理最佳实践
android·java·kotlin
sakoba41 分钟前
Tomcat简述介绍
java·tomcat
风逸hhh1 小时前
python打卡day29@浙大疏锦行
开发语言·前端·python
ᖰ・◡・ᖳ2 小时前
JavaScript:PC端特效--缓动动画
开发语言·前端·javascript·css·学习·html5
hy____1232 小时前
C++多态的详细讲解
开发语言·c++
小葡萄20252 小时前
黑马程序员C++2024版笔记 第0章 C++入门
开发语言·c++·笔记
键盘客2 小时前
Spring Boot 配置明文密码加密,防泄漏
java·spring boot·后端·spring
万物此臻2 小时前
C#编写软件添加菜单栏
开发语言·c#