我正在使用yup模块来验证我的表单。我想访问parent来测试这个值。
我的方案:
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可以在同一级别上访问,但不能在父级上访问。
有谁有主意吗?
发布于 2020-06-02 17:53:57
我也遇到过类似的问题。我成功地使用了这个解决方案。
Idea:将整个表单数据作为上下文传递给模式,并使用
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
}),
}),
});传递上下文
不带Formik的
验证时将表单数据作为上下文发送
schema.validateSync(data, {context: form_data})带Formik的
使用validate而不是validationSchema
在validateYupSchema中将您的表单数据作为第四个参数传递,它表示上下文,稍后可以在模式中访问。
在validateYupSchema.中将您的架构作为第二个参数传递
<Formik
validate={(value) => {
try {
validateYupSchema(value, schema, true, value);
} catch (err) {
return yupToFormErrors(err); //for rendering validation errors
}
return {};
}}
onSubmit={} />发布于 2019-09-19 17:52:47
您可以使用https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema中提供的测试方法。就像下面的例子一样,你可以使用this.parent在test()中访问一个级别的父细节。
amount: Yup.string().test('amount-test3', 'amount is required', function (value) {
const { description } = this.parent;
return !(!!description && !Number(value));
})https://stackoverflow.com/questions/56125797
复制相似问题