Validation 如何在yup验证中访问数组中的父值
我已经定义了一个yup模式Validation 如何在yup验证中访问数组中的父值,validation,yup,Validation,Yup,我已经定义了一个yup模式 export const ValidationSchema = yup.object().shape({ dateTo: yup .date() .required(MandatoryFieldMessage) uebernachtungen: yup.array().of( yup.object().shape({ ort: yup .string()
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") }))
})
我只想在数组中使用dateTo
的值,以便uebernachtungen
中的所有bis
都不允许其值大于dateTo
问题是我可以访问数组内的项,如ort
,但无法访问数组外的项,如dateTo
因此在本例中,yup.ref(“dateTo”)将返回未定义的,但yup.ref(“ort”)
将是正确的。数组似乎有自己的上下文,我无法访问父上下文
这怎么可能呢?如果我正确理解了你的问题,像这样的事情可能会奏效
我也遇到过类似的问题。我成功地完成了这项工作 Idea:将整个表单数据作为上下文传递给架构,并使用
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 }),
})) })
传递上下文
不带Formik
验证时将您的表单数据作为上下文发送
ValidationSchema.validateSync(data, {context: form_data})
使用Formik
使用验证代替验证方案
将您的表单数据作为validateYupSchema中的第四个参数传递,该参数表示上下文,稍后可在模式中访问
将您的模式作为validateYupSchema中的第二个参数传递
<Formik
validate={(value) => {
try {
validateYupSchema(value, ValidationSchema, true, value);
} catch (err) {
return yupToFormErrors(err); //for rendering validation errors
}
return {};
}}
onSubmit={} />
{
试一试{
ValidateUpschema(值,ValidationSchema,true,值);
}捕捉(错误){
返回yupToFormErrors(err);//用于呈现验证错误
}
返回{};
}}
onSubmit={}/>
你能分享一个可复制的例子吗,或者至少发布整个架构。@MuhammadAli我更新了它。你能告诉我你想用dateTo值实现什么吗?我想所有bis
内部UEBENACHTUNGEN
的值都不能大于dateTo
你试过“测试”吗?我已经试过了。这不会起作用,因为dateTo
不是数组上下文的一部分。您可以使用.test('test','test',function(item){console.log(This.parent)})获取它,其中This.parent是您的整个yup方案,因此您可以获得类似const{dateTo}=This.parent的内容