#javascript #reactjs #forms #formik #yup
#javascript #reactjs #формы #formik #да
Вопрос:
У меня есть 3 поля, которые по умолчанию не требуются. Однако правило требует, чтобы, если указано какое-либо из 3 полей, то все 3 будут обязательными.
Пример field_1, field_2 и field_3
validataionSchema = Yup.object({
title: Yup.string().max(10, "Max character exceeded").required("This field is required"),
field_1: Yup.string().max(32, "Max character exceeded"),
field_2: Yup.string().max(32, "Max character exceeded"),
field_3: Yup.string().max(32, "Max character exceeded"),
})
Я пробовал
validataionSchema = Yup.object({
title: Yup.string().max(10, "Max character exceeded").required("This field is required"),
field_1: Yup.string().max(15, "Max character exceeded")
.when(['field_2', 'field_3'], {
is: (field_2, field_3) => {
console.log("* field_2, field_3", field_2, field_3)
return true
},
then: Yup.string().required("This field is required")
}),
field_2: Yup.string().max(64, "Max character exceeded")
.when(['field_1', 'field_3'], {
is: (field_1, field_3) => {
console.log("** field_1, field_3", field_1, field_3)
return true
},
then: Yup.string().required("This field is required")
}),
field_3: Yup.string().max(64, "Max character exceeded")
.when(['field_1', 'field_2'], {
is: (field_1, field_2) => {
console.log("*** field_1, field_2", field_1, field_2)
return true
},
then: Yup.string().required("This field is required")
}),
})
Но я получаю Error: Cyclic dependency, node was:"field_2"
Ответ №1:
В интересах всех, кто может быть заинтересован в решении
field_1: Yup.string().max(15, "Max character exceeded")
.test("field_1", "This field is required as part of Fields details", function(value) {
let f2 = this.resolve(Yup.ref("field_2"));
let f3 = this.resolve(Yup.ref("field_3"));
if ((typeof value === "undefined" amp;amp; typeof f2 === "undefined" amp;amp; typeof f3 === "undefined") || typeof value !== "undefined") {
return true
}
return false;
}),
field_2: Yup.string().max(64, "Max character exceeded")
.test("field_2", "This field is required as part of Fields details", function(value) {
let f1 = this.resolve(Yup.ref("field_1"));
let f3 = this.resolve(Yup.ref("field_3"))
if ((typeof value === "undefined" amp;amp; typeof f1 === "undefined" amp;amp; typeof f3 === "undefined") || typeof value !== "undefined") {
return true
}
return false;
}),
field_3: Yup.string().max(64, "Max character exceeded")
.test("field_3", "This field is required as part of Fields details", function(value) {
let f1 = this.resolve(Yup.ref("field_1"));
let f2 = this.resolve(Yup.ref("field_2"));
if ((typeof value === "undefined" amp;amp; typeof f1 === "undefined" amp;amp; typeof f2 === "undefined") || typeof value !== "undefined") {
return true
}
return false;
}),