gpt4 book ai didi

javascript - Formik 中的日期验证 : 'Date of purchase' must be earlier than 'Date of sale'

转载 作者:行者123 更新时间:2023-12-02 23:06:38 24 4
gpt4 key购买 nike

我正在 React、Formik 和 Yup 中创建一个带有日期验证的简单表单。

如下所示,只有两个字段:datePurchasedateSale。我为两者设置了 minmax 参数,并根据需要设置它们:

<Formik
initialValues={{
datePurchase: '',
dateSale: '',
}}
validationSchema={object()
.shape({
datePurchase: date()
.min(new Date('01-01-2019'))
.max(new Date())
.required(),
dateSale: date()
.min(new Date('01-01-2019'))
.max(new Date())
.required(),
})}
>
{({
values, handleChange, handleBlur,
}) => (
<Form>
<input
name="datePurchase"
type="date"
onChange={handleChange}
onBlur={handleBlur}
value={values.datePurchase}
/>
<input
name="dateSale"
type="date"
onChange={handleChange}
onBlur={handleBlur}
value={values.dateSale}
/>
</Form>
)}
</Formik>

然后,我意识到datePurchase一定早于dateSale

如何使用 validationSchema() 和 Yup 来实现这样的条件?这可能吗?

我尝试将 Yup 文档中的 when() 方法与 is:then: 参数一起使用,但无济于事。

最佳答案

Yup.ref 允许您引用其他 sibling - https://github.com/jquense/yup#yuprefpath-string-options--contextprefix-string--ref

尝试一下:

validationSchema={object()
.shape({
datePurchase: date()
.min(Yup.ref('dateSale')
.max(new Date())
.required(),
dateSale: date()
.min(new Date('01-01-2019'))
.max(new Date())
.required(),
})}

关于javascript - Formik 中的日期验证 : 'Date of purchase' must be earlier than 'Date of sale' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57560082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com