/**
 * 校验异常类
 */
public class ValidateException extends RuntimeException {
    public ValidateException(String message) {
        super(message);
    }
}

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdcardUtil;

/**
 * 参数校验工具类
 */
public class ValidateUtils {

    /**
     * 非空校验
     * @param obj 待校验对象
     * @param fieldName 字段名称(用于异常提示)
     */
    public static void notNull(Object obj, String fieldName) {
        if (obj == null || (obj instanceof String && "".equals(((String) obj).trim()))) {
            throw new ValidateException(fieldName + "不能为空");
        }
    }

    /**
     * 手机号校验(中国大陆)
     * @param phone 手机号
     * @param fieldName 字段名称(用于异常提示)
     */
    public static void validatePhone(String phone, String fieldName) {
        notNull(phone, fieldName);
        if (!Validator.isMobileCN(phone)) {
            throw new ValidateException(fieldName + "格式不正确");
        }
    }

    /**
     * 身份证号校验(支持15/18位,含校验码验证)
     * @param idCard 身份证号
     * @param fieldName 字段名称(用于异常提示)
     */
    public static void validateIdCard(String idCard, String fieldName) {
        notNull(idCard, fieldName);
        if (!IdcardUtil.isValidCard(idCard)) {
            throw new ValidateException(fieldName + "格式不正确或无效");
        }
    }

    /**
     * 字符串长度校验
     * @param str 字符串
     * @param min 最小长度
     * @param max 最大长度
     * @param fieldName 字段名称(用于异常提示)
     */
    public static void validateLength(String str, int min, int max, String fieldName) {
        notNull(str, fieldName);
        int length = str.trim().length();
        if (length < min || length > max) {
            throw new ValidateException(fieldName + "长度必须在" + min + "-" + max + "之间");
        }
    }
}

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐