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

如何修改Yup日期验证规则禁止起止日期时间相同?

解决起止日期时间禁止相同的校验问题

修改Yup验证规则

当前的min方法会允许结束日期等于开始日期,要实现严格的"早于"校验,需要替换为自定义test校验逻辑,直接比较两个日期的时间戳:

const licenseSchema = Yup.object().shape<ObjectSchemaDefinition<FormData>>({
  licenseStart: Yup.date(),
  licenseEnd: Yup.date().when('licenseStart', {
    is: (start) => start != null,
    then: (end) => end.test(
      'end-after-start',
      'License end date must be later than start date',
      function(value) {
        const startDate = this.parent.licenseStart;
        return startDate ? value && value.getTime() > startDate.getTime() : true;
      }
    ),
  }),
});

说明

  • 用test方法自定义校验逻辑,通过getTime()获取两个日期的时间戳做比较,确保结束日期的时间戳严格大于开始日期,从根源上禁止两者完全相同。
  • 如果业务需要强制两个字段必填,可以给licenseStart和licenseEnd追加.required()规则。

字段配置优化(可选)

为了提升用户体验,可以给结束日期组件动态设置最小可选时间,避免用户选到与开始日期相同的时间:

import { useFormContext } from 'react-hook-form';

const LicenseDateFields = () => {
  const { watch } = useFormContext();
  const startDate = watch('licenseStart');

  return (
    <>
      <Field name="licenseStart" label="From" as={DateTimeTextField} />
      <Field 
        name="licenseEnd" 
        label="To" 
        as={DateTimeTextField} 
        props={{
          minDate: startDate ? new Date(startDate.getTime() + 1) : undefined,
        }}
      />
    </>
  );
};

说明

  • 通过watch监听开始日期的变化,将结束日期的最小可选值设为开始日期的下一秒,用户在选择时就无法直接选中与开始日期完全相同的时间。
  • props用于传递组件的属性,具体格式需匹配你使用的DateTimeTextField组件要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:01:45