我正在使用Formik和yup来验证它。我对两个字段
的验证有以下要求startedended
started必须是有效日期。started必须是过去的日期。ended可以为 null,表示不需要。ended不能为空,并且如果started
具有有效的日期值,则必须是有效的日期。这是我的验证架构:
validationSchema={yup.object().shape({
started: yup.date().max(new Date(), "Future date not allowed").typeError("Invalid Started date"),
ended: yup.date().default(null).when("started", {
is: yup.date().isValid(),
then: yup.date().min(yup.ref("started"), "Ended date must be later than Start date"),
otherwise: yup.date().nullable()
}).typeError("Invalid Ended date")
})}
Run Code Online (Sandbox Code Playgroud)
1、2、3 有效,但第四次验证无效。
我也尝试将其更改为is: started => started !==null,这是完全错误的,因为我console.log(started)和那打印了我Invalid date。
我什至尝试过is: true也没有成功。
验证此要求的正确方法是什么?
我有一个使用 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 …