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

如何在Yup错误消息中显示字段当前字符数?

Yup数组字段动态显示字符数错误消息

问题场景

当前使用Yup的验证Schema如下:

const validationSchema = Yup.object().shape({
  statuses: Yup.array().of(
    Yup.object().shape({
      value: Yup.string().when('deleted', {
        is: false,
        then: Yup.string()
          .nullable()
          .max(64, 'Must be less than 64 characters'),
      }),
      available_on_label: Yup.string().when('deleted', {
        is: false,
        then: Yup.string()
          .nullable()
          .max(15, 'Must be less than 15 characters'),
      }),
    })
  ),
})

需要实现available_on_label字段的错误消息动态显示当前输入的字符数,格式如:Must be less than 15 characters. (${当前字符数} / 15),但直接在验证规则中访问字符串内容无法实现。

解决方法

Yup的.max()方法支持传入函数作为错误消息,函数会接收当前字段值value和验证上下文context两个参数,以此实现动态消息生成。

1. 修改.max()规则为函数形式

替换固定错误消息为函数,计算当前值的长度:

const validationSchema = Yup.object().shape({
  statuses: Yup.array().of(
    Yup.object().shape({
      value: Yup.string().when('deleted', {
        is: false,
        then: Yup.string()
          .nullable()
          .max(64, 'Must be less than 64 characters'),
      }),
      available_on_label: Yup.string().when('deleted', {
        is: false,
        then: Yup.string()
          .nullable()
          .max(15, (value) => {
            // 处理null/undefined,避免长度读取报错
            const currentLength = value ? value.length : 0;
            return `Must be less than 15 characters. (${currentLength} / 15)`;
          }),
      }),
    })
  ),
})

2. 访问数组项的其他字段(可选)

如果需要在错误消息中引用当前数组项的其他字段(比如deleted),可以通过context.parent获取:

.max(15, (value, context) => {
  const currentLength = value ? value.length : 0;
  const isDeleted = context.parent.deleted;
  return isDeleted 
    ? '' 
    : `Must be less than 15 characters. (${currentLength} / 15)`;
})

注意点

  • 必须处理value为null或undefined的情况,否则会触发Cannot read property 'length' of null错误。
  • .when()规则确保只有deleted为false时,该验证逻辑才会执行,函数也只会在需要验证的场景下触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:20:23