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

注解

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();
    }
}
相关推荐
心平愈三千疾30 分钟前
通俗理解JVM细节-面试篇
java·jvm·数据库·面试
我不会写代码njdjnssj32 分钟前
网络编程 TCP UDP
java·开发语言·jvm
第1缕阳光36 分钟前
Java垃圾回收机制和三色标记算法
java·jvm
funnyZpC1 小时前
好用的文档工具👉smart-doc
java
一只叫煤球的猫1 小时前
🔥 同事混用@Transactional和TransactionTemplate被我怼了,三种事务管理到底怎么选?
java·spring boot·后端
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
阿蒙Amon9 天前
《C#图解教程 第5版》深度推荐
开发语言·c#
学Linux的语莫9 天前
python基础语法
开发语言·python
暖馒9 天前
C#委托与事件的区别
开发语言·c#
华子w9089258599 天前
基于 SpringBoot+JSP 的医疗预约与诊断系统设计与实现
java·spring boot·后端