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

如何将Yup的date()方法适配为巴西(dd/MM/YYYY)日期格式

Yup 校验 dd/MM/YYYY 格式日期的实现方案

Yup 默认的 .date() 方法仅支持识别 ISO 标准日期格式,要适配巴西/欧洲通用的 dd/MM/YYYY 格式,可使用以下两种方案:

方案1:自定义校验规则(无额外依赖)

直接通过 Yup 的 test() 方法自定义校验逻辑,同时校验格式合法性与日期本身有效性:

import * as Yup from 'yup';

const schema = Yup.object({
  birthday: Yup.string()
    .required('生日为必填项')
    .test('date-valid', '请输入合法的日期格式 dd/MM/YYYY', (value) => {
      if (!value) return false;
      // 匹配dd/MM/YYYY格式
      const dateReg = /^(\d{2})\/(\d{2})\/(\d{4})$/;
      if (!dateReg.test(value)) return false;
      
      const [, day, month, year] = value.match(dateReg);
      // 转成数字校验范围
      const d = parseInt(day, 10);
      const m = parseInt(month, 10);
      const y = parseInt(year, 10);
      
      // 月份范围1-12
      if (m < 1 || m > 12) return false;
      // 日期范围适配当月天数
      const daysInMonth = new Date(y, m, 0).getDate();
      if (d < 1 || d > daysInMonth) return false;
      
      // 可选:增加生日的逻辑校验,比如不能是未来日期
      const inputDate = new Date(y, m - 1, d);
      return inputDate <= new Date();
    })
});

方案2:格式转换后使用默认date校验

如果需要最终输出日期对象,可通过 transform() 方法先把输入的字符串转成合法 Date 对象,再走默认日期校验:

需提前安装 dayjs/date-fns 等日期处理库,示例使用 dayjs

import * as Yup from 'yup';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);

const schema = Yup.object({
  birthday: Yup.date()
    .required('生日为必填项')
    .typeError('请输入合法的日期格式 dd/MM/YYYY')
    .transform((_, originalValue) => {
      // 解析dd/MM/YYYY格式的字符串为日期对象
      const parsedDate = dayjs(originalValue, 'DD/MM/YYYY', true);
      return parsedDate.isValid() ? parsedDate.toDate() : new Date('');
    })
    .max(new Date(), '生日不能是未来日期')
});

两种方案都可以正常识别 dd/MM/YYYY 格式的日期,可根据自己是否需要输出 Date 对象选择对应的实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:39:05