我正在使用 yup
用于验证我的表单的模块。我想访问父级以测试该值。
我的架构:
enabled: yup.boolean(),
contactDetail: yup.object().shape({
phoneNumber1: yup.string().nullable(),
phoneNumber2: yup.string().nullable(),
email: yup.string().test('email', 'test', async function() {
// test enabled value
})
}),
方法
when
可以在同一级别访问,而不是父级。有人有想法吗?
最佳答案
我遇到了类似的问题。我成功地使用了这个解决方法。
理念 :将整个表单数据作为上下文传递给架构并使用访问任何表单值
this.options.context
const schema = yup.object().shape({
enabled: yup.boolean(),
contactDetail: yup.object().shape({
phoneNumber1: yup.string().nullable(),
phoneNumber2: yup.string().nullable(),
email: yup.string().test('email', 'test', async function () {
// this.options.context.enabled
}),
}),
});
Passing Context
没有Formik
发送您的表格数据作为验证时的上下文
schema.validateSync(data, {context: form_data})
与 Formik
使用验证 而不是 验证架构
通过您的表格数据作为 中的第四个参数validateYupSchema 它表示上下文,以后可以在模式中访问。
通过您的架构 作为 中的第二个参数validateYupSchema .
<Formik
validate={(value) => {
try {
validateYupSchema(value, schema, true, value);
} catch (err) {
return yupToFormErrors(err); //for rendering validation errors
}
return {};
}}
onSubmit={} />
关于javascript - 是的,验证访问 parent.parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56125797/