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

如何使用Yup对非必填表单字段实现填写后的规则校验?

Yup非必填字段有值才验证的实现方案

你可以直接在lastname的验证规则后追加格式和长度验证规则,配合字段转换逻辑即可实现需求,完整验证schema如下:

const validationSchema = Yup.object().shape({
    firstname: Yup.string()
        .required("First name is required")
        // 修正原正则:匹配全字母,避免出现字母加其他字符也能通过验证的问题
        .matches(/^[A-Za-z]+$/, "Should contain only alphabets")
        // 修正原语法错误:统一模板字符串的反引号包裹
        .min(3, `Should contain at least ${min} alphabets`)
        .max(20, `Should not exceed ${max} alphabets`),
    lastname: Yup.string()
        .nullable()
        // 空字符串自动转null,命中非必填跳过验证的逻辑
        .transform((value) => value?.trim() || null)
        .notRequired()
        .matches(/^[A-Za-z]+$/, "Last name should contain only alphabets")
        .min(2, `Last name should contain at least ${min} alphabets`)
        .max(20, `Last name should not exceed ${max} alphabets`)
})

规则说明

  • transform((value) => value?.trim() || null):将用户输入的空白内容(全空格、空字符串)自动转换为null,避免空白内容触发后续验证
  • notRequired()声明字段非必填,当值为null/undefined时,后续的格式、长度验证规则会自动跳过
  • 仅当用户实际输入了非空白内容时,后面的字母校验、长度校验规则才会生效

如果需要更显式的条件判断逻辑,也可以使用when方法实现:

lastname: Yup.string()
  .nullable()
  .trim()
  .notRequired()
  .when('lastname', {
    is: (value) => Boolean(value),
    then: (schema) => schema
      .matches(/^[A-Za-z]+$/, "Last name should contain only alphabets")
      .min(2, `Last name should contain at least ${min} alphabets`)
      .max(20, `Last name should not exceed ${max} alphabets`)
  })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:57:03