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

如何用Yup正确验证可空、可选且非空时长度≥2的字符串?

Yup验证字符串:允许null/空字符串,有值时长度需大于2的正确写法

需求规则:

  • 字段为字符串类型
  • 允许为null或空字符串
  • 若字段有值,则长度必须大于2(即长度≥2)

原schema无法通过空字符串的验证,问题在于min(2)会对所有存在的字符串(包括空字符串)执行校验,而.optional()和.notRequired()仅允许字段不存在,不影响空字符串的校验逻辑。

解决方案

方法1:自定义.test()校验

直接编写测试逻辑,当值为null或空字符串时跳过长度校验:

const schema = object({
  firstname: string()
    .nullable()
    .optional()
    .test(
      'min-length',
      '长度必须大于2',
      (value) => value === null || value === '' || value.length >= 2
    ),
});

方法2:.when()条件校验

通过条件判断,仅当值不为null且不为空字符串时,应用min(2)规则:

const schema = object({
  firstname: string()
    .nullable()
    .optional()
    .when('firstname', {
      is: (val) => val !== null && val !== '',
      then: (schema) => schema.min(2, '长度必须大于2'),
    }),
});

验证结果

修改后的schema可正确匹配预期测试用例:

  • ✅ { firstname: 'bla' }(长度符合要求)
  • ✅ { firstname: '' }(允许空字符串)
  • ✅ { firstname: null }(允许null)
  • ❌ { firstname: 'a' }(长度不足)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:01:10