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

注解

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();
    }
}
相关推荐
军训猫猫头16 分钟前
11.用反射为静态类的属性赋值 C#例子 WPF例子
开发语言·c#
傻啦嘿哟20 分钟前
Python3解释器深度解析与实战教程:从源码到性能优化的全路径探索
开发语言·python
xcnwldgxxlhtff29 分钟前
Java:线程池
java·开发语言
弹简特36 分钟前
【Java web】HTTP 与 Web 基础教程
java·开发语言·前端
字节跳跃者1 小时前
Java 中的 Stream 可以替代 for 循环吗?
java·后端
北执南念1 小时前
如何在 Spring Boot 中设计和返回树形结构的组织和部门信息
java·spring boot·后端
遗憾皆是温柔1 小时前
19. 重载的方法能否根据返回值类型进行区分
java·开发语言·面试·学习方法
ts码农1 小时前
model层实现:
java·服务器·前端
泰勒疯狂展开2 小时前
Java研学-RabbitMQ(六)
java·rabbitmq·java-rabbitmq
Warren982 小时前
Java Record 类 — 简化不可变对象的写法
java·开发语言·jvm·分布式·算法·mybatis·dubbo