根据Yup和Formik中的另一个字段有条件地验证字段 [英] Validate fields conditionally based on another field in Yup and Formik
本文介绍了根据Yup和Formik中的另一个字段有条件地验证字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在验证时遇到问题.我希望如果access
的值为1,那么您可以选择start_date
和end_date
但是,如果access
的值不为1,那么您只能选择今天.
I have a problem in validation. I wanted that if access
value is 1 then you can select the start_date
and end_date
BUT if the value of access
is not 1, then you can only select today.
Codesandbox
Codesandbox
export const validationSchema = yup.object().shape({
access: yup.number().nullable(),
start_date: yup.string().required('Select start date'),
end_date: yup.string().required('Select end date'),
});
推荐答案
您可以使用日期验证来代替字符串验证,而请确保设置正确的消息传递!:
Instead of string validation you can use date validation, just make sure to set correct messaging!:
import moment from "moment";
...
const today = new Date().toDateString();
const validationSchema = yup.object().shape({
access: yup.number().nullable(),
start_date: yup.date()
.typeError("Invalid date")
.required("Select start date")
.when("access", {
is: 1,
otherwise: (d) => d.min(today, "Should be today's date")
.max(today, "Should be today's date")
}),
end_date: yup.date()
.typeError("Invalid date")
.required("Select end date")
.when("access", {
is: 1,
otherwise: (d) => d.min(today, "Should be today's date")
.max(today, "Should be today's date")
})
});
可以找到更新的堆栈闪电这里.
Update stackblitz can be found here.
这篇关于根据Yup和Formik中的另一个字段有条件地验证字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文