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

如何用Yup实现多字段条件OR验证及日期大小校验?

Yup 实现日期字段验证方案

针对你给出的三个字段:

dateType: null | String,
fromDate: null | Date,
toDate: null | Date,

下面是满足你两个验证需求的Yup实现方案:

完整验证Schema代码

import * as Yup from 'yup';

const validationSchema = Yup.object().shape({
  dateType: Yup.string().nullable(),
  fromDate: Yup.date().nullable(),
  toDate: Yup.date().nullable(),
}).test(
  'date-required-when-type-set',
  '选择日期类型后,必须填写开始日期或结束日期',
  function(value) {
    const { dateType, fromDate, toDate } = this.parent;
    // 当dateType不为null时,fromDate或toDate至少有一个不为null
    if (dateType !== null && !fromDate && !toDate) {
      return false;
    }
    return true;
  }
).test(
  'from-date-earlier-than-to-date',
  '开始日期不能晚于结束日期',
  function(value) {
    const { fromDate, toDate } = this.parent;
    // 只有当两个日期都存在时,才验证先后顺序
    if (fromDate && toDate && fromDate >= toDate) {
      return false;
    }
    return true;
  }
);

逻辑说明

  1. 日期类型非空时的必填验证
    通过全局test方法监听整个表单对象,当dateType不为空时,检查fromDate和toDate是否至少有一个被填写。如果都为空,则返回验证失败,抛出自定义错误信息。

  2. 双日期存在时的顺序验证
    同样使用全局test方法,当fromDate和toDate都存在时,判断fromDate是否早于toDate。如果开始日期大于等于结束日期,返回验证失败。

可选优化:字段级条件验证

如果你希望把验证逻辑绑定到具体字段上(比如错误提示关联到对应输入框),可以改用when方法实现:

const validationSchema = Yup.object().shape({
  dateType: Yup.string().nullable(),
  fromDate: Yup.date()
    .nullable()
    .when('dateType', {
      is: (val) => val !== null,
      then: (schema) => schema.test(
        'at-least-one-date',
        '选择日期类型后,必须填写开始日期或结束日期',
        function(value) {
          return value || this.parent.toDate;
        }
      )
    })
    .when('toDate', {
      is: (val) => val !== null,
      then: (schema) => schema.max(Yup.ref('toDate'), '开始日期不能晚于结束日期')
    }),
  toDate: Yup.date()
    .nullable()
    .when('dateType', {
      is: (val) => val !== null,
      then: (schema) => schema.test(
        'at-least-one-date',
        '选择日期类型后,必须填写开始日期或结束日期',
        function(value) {
          return value || this.parent.fromDate;
        }
      )
    })
    .when('fromDate', {
      is: (val) => val !== null,
      then: (schema) => schema.min(Yup.ref('fromDate'), '结束日期不能早于开始日期')
    }),
});

这种方式会把错误提示直接关联到对应的日期输入框,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:45:33