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

如何通过Yup根据delete属性值控制rate验证?当前代码遇NaN问题

问题解决:Joi条件验证rate字段的正确写法

你的问题出在规则逻辑顺序和类型验证的覆盖上,原代码先强制rate为必填数字,后续的when规则没彻底覆盖前置的必填要求,而且当delete=true时仍在强制验证rate的数字类型,导致未传rate时被Joi转换为NaN。

正确写法示例

以下两种写法都能实现需求:

写法一:使用when的then/otherwise分支

charges: array().nullable().of(
  object().shape({
    rate: number()
      .when("delete", {
        is: false,
        then: (schema) => schema.required().typeError("Rate missing"),
        otherwise: (schema) => schema.optional().allow(null, '') // 允许不存在、空值,避免类型转换产生NaN
      })
  })
),

写法二:使用多分支when规则

charges: array().nullable().of(
  object().shape({
    rate: when("delete", [
      { is: false, then: number().required().typeError("Rate missing") },
      { is: true, then: any().optional() } // delete=true时,rate可填可不填,不做类型限制
    ])
  })
),

关键说明

  • 原代码的required()是全局规则,后续的notRequired()无法完全覆盖,必须把必填逻辑放在when的条件分支里。
  • 当delete=true时,要明确允许rate字段不存在或为非数字值,避免Joi自动尝试类型转换导致NaN。

内容的提问来源于stack exchange,提问作者Sachith Deshan N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:39:08