我已经定义了一个 yup 模式
export const ValidationSchema = yup.object().shape({
dateTo: yup
.date()
.required(MandatoryFieldMessage)
uebernachtungen: yup.array().of(
yup.object().shape({
ort: yup
.string()
.trim()
.max(100, Maximum100CharactersMessage)
.required(MandatoryFieldMessage),
bis: yup
.date()
.required(MandatoryFieldMessage)
.max(yup.ref("dateTo"), "display message") }))
})
Run Code Online (Sandbox Code Playgroud)
我只想使用dateTo数组内部的值,这样所有的bis值都uebernachtungen不允许大于dateTo。
问题是我可以访问数组内部的项目,ort但我无法访问其中的项目,例如dateTo。
因此,在这种情况下 yup.ref("dateTo") 将返回未定义但yup.ref("ort")正确的。数组似乎有自己的上下文,我无法访问父上下文。
这怎么可能呢?
I came through similar issue. I used this workthrough with success.
Idea: Pass whole form-data as a context to the schema and access any form value using
this.options.context
const ValidationSchema = yup.object().shape({
dateTo: yup
.date()
.required(MandatoryFieldMessage)
uebernachtungen: yup.array().of(
yup.object().shape({
ort: yup
.string()
.trim()
.max(100, Maximum100CharactersMessage)
.required(MandatoryFieldMessage),
bis: yup
.date()
.required(MandatoryFieldMessage)
.test('dateToCheck', 'display message', function (value) {
// access dateTo from passed context
if(value>this.options.context.dateTo) return false
return true }),
})) })
Run Code Online (Sandbox Code Playgroud)
Passing Context
Without Formik
Send your Form data as a context while validating
ValidationSchema.validateSync(data, {context: form_data})
Run Code Online (Sandbox Code Playgroud)
With Formik
Use validate instead of validationSchema
Pass your Form data as 4th argument in validateYupSchema which represents context and can be accessed later in schema.
Pass your schema as 2nd argument in validateYupSchema.
<Formik
validate={(value) => {
try {
validateYupSchema(value, ValidationSchema, true, value);
} catch (err) {
return yupToFormErrors(err); //for rendering validation errors
}
return {};
}}
onSubmit={} />
Run Code Online (Sandbox Code Playgroud)