javascript - 是的日期验证+ 1天
问题描述
我有一个使用 formik / yup 的表格,我正在对照表格中的其他日期验证日期。我有一个字段expirationDate
,我希望至少在输入表单的第二天之后出现。 enteredDate
我目前有这个,它可以工作,但可以验证enteredDate
- 问题是如果您将 06/21/21 设置为输入的日期,它接受 06/21/21 作为到期日期 - 我需要将其设置为 06/ 22/21 作为最短日期,或enteredDate + 1 day
.
yup.date('Expiration Date')
.nullable()
.min(yup.ref('enteredDate'),
({ min }) => `Expiration Date needs to be after Entered Date`
)
我尝试了很多变体
yup.date('Expiration Date')
.nullable()
.min(yup.ref('enteredDate') ? daysjs(yup.ref('enteredDate').add(1, 'day') : null,
({ min }) => `Expiration Date needs to be after Entered Date`
)
但yup.ref
似乎没有返回日期对象,因为错误是TypeError: The value of field could not be cast to a value that satisfies the schema type: "date".
我怎样才能告诉 yup 第二天使用?
解决方案
您需要使用.when
方法将一个字段连接到另一个字段。文档。
这应该按预期工作:
const schema = object({
enteredDate: date().required(),
expirationDate: date().when("enteredDate", (enteredDate, schema) => {
if (enteredDate) {
// This can be calculated in many ways. Just be sure that its type is `Date` object
const dayAfter = new Date(enteredDate.getTime() + 86400000);
return schema.min(dayAfter);
}
return schema;
})
});
推荐阅读
- node.js - Nodejs等待/异步问题
- windows - 我可以在 Windows 上手动选择 .ssh 默认文件夹吗?
- javascript - 缩放类添加到滑块中的所有图像而不检查“li”是否处于活动状态
- javascript - 覆盖窗口上的函数
- notepad++ - 使用记事本++将两行合并为一行
- python - 使用 boost::python::make_function 设置 __name__ 属性
- reactjs - 通知配置文件中的函数安装了组件
- sql - 计算订单列表中的重复出现次数
- kubernetes - 为什么我的 ALB 端点上出现针对 EKS 托管服务的 502 错误
- sql - 与 > 的日期时间比较不起作用