You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript Schema手机号验证器兼容空字符串的实现问题

解决方案

你遇到的问题是optional: true仅允许字段不存在时跳过校验,但当字段存在且为空字符串时,依然会执行matches等校验规则。要同时支持空字符串和合法手机号,可通过以下两种方式实现:

方法一:自定义校验逻辑

在custom规则里直接判断:如果是trim后的空字符串则通过,否则执行原有的手机号格式校验:

private static model: Schema = {
  'user.phone': {
    in: 'body',
    isString: true,
    trim: true,
    custom: {
      options: (value: string) => {
        // 空字符串直接通过
        if (value === '') return true;
        // 否则执行原有手机号格式校验
        const phoneRegex = /^\(?[1-9]{2}\)?(?:[2-8]|9[1-9])[0-9]{3}-?[0-9]{4}$/;
        return phoneRegex.test(value);
      }
    },
    customSanitizer: {
      options: (value: string) => {
        return value.replace(/[^0-9]/g, '');
      }
    },
    errorMessage: 'Invalid phone number'
  },
};

方法二:组合校验场景

用oneOf规则定义两组校验逻辑:一组接受空字符串,另一组执行原有的手机号格式校验:

private static model: Schema = {
  'user.phone': {
    in: 'body',
    isString: true,
    trim: true,
    oneOf: [
      // 场景1:空字符串
      {
        matches: {
          options: [/^$/],
        }
      },
      // 场景2:合法手机号格式
      {
        matches: {
          options: [/^\(?[1-9]{2}\)?(?:[2-8]|9[1-9])[0-9]{3}-?[0-9]{4}$/]
        }
      }
    ],
    customSanitizer: {
      options: (value: string) => {
        return value.replace(/[^0-9]/g, '');
      }
    },
    errorMessage: 'Invalid phone number'
  },
};

补充说明

如果需要同时允许字段未提交、提交为空字符串、提交合法手机号三种情况,可在规则里额外加上optional: true。

内容的提问来源于stack exchange,提问作者Paula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:01:19