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

React项目中Yup手机号验证:允许空值或13位长度的实现

解决Yup手机号空值或固定长度校验问题

问题说明

你之前使用.nullable()无效,是因为这个方法仅允许字段值为null,但空字符串""不属于null范畴,所以需要同时处理空字符串的场景。

方案一:自定义test校验(直观易懂)

通过test方法直接判断:空值(null/空字符串/未定义)直接通过,非空值必须满足13位长度:

const schema = yup.object().shape({
  phone: yup.string()
    .nullable() // 允许字段为null
    .optional() // 允许字段为空字符串或未定义
    .test(
      'phone-validation',
      'Invalid number',
      (value) => !value || value.length === 13
    )
});

方案二:正则匹配(简洁写法)

用正则表达式匹配空字符串或13位长度的内容:

const schema = yup.object().shape({
  phone: yup.string()
    .nullable()
    .optional()
    .matches(/^$|^.{13}$/, "Invalid number")
});

方案三:转换空字符串为null

通过transform把空字符串转为null,再结合.nullable()让空值跳过长度校验:

const schema = yup.object().shape({
  phone: yup.string()
    .transform((val) => val === "" ? null : val)
    .nullable()
    .min(13, "Invalid number")
});

这种方式下,空字符串会被转换成null,.nullable()允许null通过校验;如果是有效输入,则必须满足13位长度要求。

内容的提问来源于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 10:55:24