[英]Yup validation based on value of another field
I've three fields: referenceMonth(string), openingDate(string), closingDate(string) in Formik form.我有三个字段:Formik 形式的referenceMonth(string)、openingDate(string)、closureDate(string)。 I would add an error to
openingDate
when openingDat
isn't the same month as referenceMonth
.当
openingDat
与referenceMonth
不同时,我会在openingDate
中添加一个错误。
export const VALIDATION_SCHEMA = Yup.object().shape({
'referenceMonth' : Yup.number().required(YUP_DEFAULT_ERROR_VALUE),
'openingDate' : Yup.string().when(['referenceMonth', 'openingDate'], {
is: (referenceMonth: string, openingDate: string) =>
referenceMonth !== `${new Date(openingDate).getMonth()}`,
then: Yup.string().required('Select right month')
}),
})
Terminal says: Error: Cyclic dependency, node was: "openingDate".终端说:错误:循环依赖,节点是:“openingDate”。
Fields that depend on each other, to be validated, needs to be sorted so that they are constructed in in the desired order.需要对相互依赖、需要验证的字段进行排序,以便按所需顺序构建它们。 Can you try it this way by adding the fields that need validation at the end in that specific order:
您可以通过以特定顺序在末尾添加需要验证的字段来尝试这种方式:
export const VALIDATION_SCHEMA = Yup.object().shape({
'referenceMonth' : Yup.number().required(YUP_DEFAULT_ERROR_VALUE),
'openingDate' : Yup.string().when(['referenceMonth', 'openingDate'], {
is: (referenceMonth, openingDate) =>
referenceMonth !== `${new Date(openingDate).getMonth()}`,
then: Yup.string().required('Select right month')
}),
}, [['referenceMonth', 'openingDate']])
Since your validation for openingDate
is pretty stright forward as in the schema for openingDate
won't change (as per my understanding), i would suggest you to make use of test
rather than when
.由于您对
openingDate
的验证非常简单,因为openingDate
的架构不会改变(根据我的理解),我建议您使用test
而不是when
。 You could replace your when
with test
like so你可以用这样的
test
替换你的when
.test("dateTest", "Select right month", function (value) {
return this.parent.referenceMonth !== `${new Date(value).getMonth()}`;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.