use*_*289 5 javascript validation yup formik
我有一个使用 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`
)
Run Code Online (Sandbox Code Playgroud)
我尝试过很多变体
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`
)
Run Code Online (Sandbox Code Playgroud)
但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;
})
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8300 次 |
| 最近记录: |