-
Hi, I have a dynamic form where nested "link" objects can be added or removed. By reading your documentation and some discussions on Github I made it work. I can populate, submit and receive the right data, but I don't know how to manage the validation for the nested objects. This is the object that the user is editing: {
subject: "This is a subject",
links: [
{
title: "Im the title for the first nested object",
url: "Im the url for the first nested object",
},
{
title: "Im the title for the second nested object",
url: "Im the url for the second nested object",
}
]
} I'm using the Composition API (with the script setup syntax) to create the form and the validation schema: const validationSchema = yupObject({
subject: yupString().required().max(50),
links: buildValidations.value, // explained later in this post
});
const { handleSubmit, errors, setValues } = useForm({
validationSchema,
});
const { value: subject } = useField('subject');
const { remove, push, fields } = useFieldArray('links'); Then I set the initial data received from an API call: setValues({
subject: data.value.subject,
links: data.value.links
}); In my template I'm using the fields variable to loop on the links, and the Field component to create the form for the nested objects <Field :name="`links[${index}].title`" v-slot="{ value, field }" >
<BaseInput
v-bind="field"
:model-value="value"
label="Title"
type="text"
:max="50"
/>
</Field>
<Field :name="`links[${index}].url`" v-slot="{ value, field }" >
<BaseInput
v-bind="field"
:model-value="value"
label="URL"
type="text"
:max="442"
/>
</Field> I'm also using the remove and push destructured variables on buttons to add or remove link items. It's working like a charm! But I don't know how to dynamically update my validation schema for the nested links objects. I found on this discussion this code: const buildValidations = computed(() => {
const yupLinks = fields.value.reduce((acc, field, index) => {
const validation = yupObject({
title: yupString().required('Your link needs a title.').max(50, 'Your link title must be maximum 50 characters.'),
url: yupString().required('Your link needs a URL to redirect to.').max(442, 'Your link URL must be maximum 442 characters.'),
});
acc[index] = validation;
return acc;
}, {});
return yupObject(yupLinks);
}); but it's not working because fields is destructured from useFieldArray after the creation of the validation schema. Could you help me? I hope my explanations are clear. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Ho sorry I misread your answer here #3617 (reply in thread) I tried your solutions of Thanks a lot for your answer. |
Beta Was this translation helpful? Give feedback.
Ho sorry I misread your answer here #3617 (reply in thread)
I tried your solutions of
Yup.array().of(Yup.object({
and it works perfectly.Thanks a lot for your answer.