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

React中使用Yup验证日期范围:结束日期必须严格大于起始日期

Fixing Yup Date Validation for Strictly Greater End Date

Got it, I get exactly what you need here—your current schema uses min(Yup.ref('startDate')) which allows the end date to match the start date, but your business rule requires it to be strictly later. Yup's built-in min doesn't support strict comparison out of the box, so we'll use a custom test to make this work.

Here's the updated validation schema that enforces the strict end date rule:

import * as Yup from 'yup';

const schema = Yup.object().shape({
  startDate: Yup.date()
    .min(new Date(), 'Please choose a future date')
    .typeError('Start Date is Required')
    .required('Start Date is Required'), // Explicit check for empty submissions
  endDate: Yup.date()
    .typeError('End Date is Required')
    .required('End Date is Required')
    .test(
      'strictly-greater-than-start',
      'End date must be strictly greater than start date',
      function(endDate) {
        const { startDate } = this.parent;
        // Compare timestamps to ensure endDate is truly later (not equal)
        return startDate && endDate && endDate.getTime() > startDate.getTime();
      }
    )
    // Optional: Uncomment if you want end date to also be a future date
    // .min(new Date(), 'End date must be a future date')
});

Key Changes Explained:

  • Custom Strict Comparison: We replaced the min(Yup.ref('startDate')) with Yup's test() method. This lets us write custom logic to check that the end date's timestamp is strictly larger than the start date's timestamp—no equality allowed.
  • Explicit Required Checks: Added required() to both fields to handle empty submissions. The typeError only triggers when the input isn't a valid date, but required() ensures users can't leave the field blank entirely.
  • Precise Timestamp Check: Using getTime() ensures we're comparing the exact moment in time, which works seamlessly whether you're using date-only pickers or datetime pickers. For example, a start date of 9 AM and end date of 9 AM will fail, but 9 AM to 10 AM will pass.

This schema will now reject any case where the end date is equal to or earlier than the start date, perfectly matching your business requirements.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 08:27:32