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

Yup日期校验实现:开始日期不得与结束日期相同(基于dayjs)

Yup日期严格大于校验方案(开始/结束日期不能相等)

核心思路

原有的yup.date().min(yup.ref('startDate'))规则是大于等于逻辑,相等日期会通过校验,因此需要使用Yup的test()方法自定义校验逻辑,实现严格大于的判断。

原生JS实现版本

无额外依赖,直接通过Date对象时间戳比较:

import * as yup from 'yup';

const schema = yup.object().shape({
  startDate: yup.date().min(new Date(),'Please choose future date').required(),
  endDate: yup
    .date()
    .required()
    .test(
      'endAfterStart',
      'End date has to be later than start date',
      function (value) {
        const { startDate } = this.parent;
        // 兼容字段未填写场景,必填校验已单独处理
        if (!startDate || !value) return true;
        // 转时间戳比较,严格大于才通过校验
        return new Date(value).getTime() > new Date(startDate).getTime();
      }
    ),
});

如果你只需要按日期(天)维度判断相等,不需要校验时分秒,可在校验前把两个日期的时分秒统一置为0再比较。

dayjs实现版本

适配项目技术栈要求:

import * as yup from 'yup';
import dayjs from 'dayjs';

const schema = yup.object().shape({
  startDate: yup.date().min(new Date(),'Please choose future date').required(),
  endDate: yup
    .date()
    .required()
    .test(
      'endAfterStart',
      'End date has to be later than start date',
      function (value) {
        const { startDate } = this.parent;
        if (!startDate || !value) return true;
        // 精确到毫秒的严格大于判断
        return dayjs(value).isAfter(startDate);
      }
    ),
});

如果需要按天维度判断(比如2024-05-20 14:00和2024-05-20 18:00视为相同日期),修改判断逻辑即可:

// isAfter第二个参数指定比较粒度,支持year/month/week/day/hour/minute等
return dayjs(value).isAfter(startDate, 'day');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:06:02