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

注解

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();
    }
}
相关推荐
Tisfy7 小时前
LeetCode 1927.求和游戏:抵消+看最值
java·leetcode·游戏·题解·博弈论
「QT(C++)开发工程师」12 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天12 小时前
0 初识C++
开发语言·c++
FfHUCisI13 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI13 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
秋饼13 小时前
JDK 27 企业级 AI 服务落地实战:G1 默认、紧凑对象头、后量子 TLS 与 JFR 脱敏全解析
java·ai·技术分享·后端开发
卓怡学长14 小时前
w176基于SpringBoot的医院管理系统
java·spring boot·spring·maven·intellij-idea
lemon_sjdk14 小时前
ObjectProperty
java·开发语言·算法
大模型码小白14 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring