Nested Objects and Arrays
vee-validate supports nested objects and arrays by using field name syntax to indicate a field’s path. This allows you to structure forms easily to make data mapping straightforward without having to deal with flat form values.
Nested Objects
You can specify a field to be nested in an object using dot paths, like what you would normally do in JavaScript to access a nested property. The field’s name
acts as the path for that field in the form values:
vue<template>
<form @submit="onSubmit">
<input v-model="twitter" type="url" />
<input v-model="github" type="url" />
<button>Submit</button>
</form>
</template>
<script setup>
import { useField, useForm } from 'vee-validate';
const { handleSubmit } = useForm();
const onSubmit = handleSubmit(values => {
alert(JSON.stringify(values, null, 2));
});
const { value: twitter } = useField('links.twitter');
const { value: github } = useField('links.github');
</script>
Submitting the previous form would result in the following values being passed to your handler:
js{
"links": {
"twitter": "https://twitter.com/logaretm",
"github": "https://github.com/logaretm"
}
}
You are not limited to a specific depth, you can nest as much as you like.
Nested Arrays
Similar to objects, you can also nest your values in an array, using square brackets just like how you would do it in JavaScript.
Here is the same example as above but in array format:
vue<template>
<form @submit="onSubmit">
<input v-model="twitter" type="url" />
<input v-model="github" type="url" />
<button>Submit</button>
</form>
</template>
<script setup>
import { useField, useForm } from 'vee-validate';
const { handleSubmit } = useForm();
const onSubmit = handleSubmit(values => {
alert(JSON.stringify(values, null, 2));
});
const { value: twitter } = useField('links[0]');
const { value: github } = useField('links[1]');
</script>
Submitting the previous form would result in the following values being passed to your handler:
js{
"links": [
"https://twitter.com/logaretm",
"https://github.com/logaretm"
]
}
warn
vee-validate will only create nested arrays if the path expression is a complete number, for example, paths like some.nested[0path]
will not create any arrays because the 0path
key is not a number. However some.nested[0].path
will create the array with an object as the first item.
Avoiding Nesting
If your fields’ names are using the dot notation and you want to avoid the nesting behavior which is enabled by default, all you need to do is wrap your field names in square brackets ([]
) to disable nesting for those fields.
vue<template>
<form @submit="onSubmit">
<input v-model="twitter" type="url" />
<input v-model="github" type="url" />
<button>Submit</button>
</form>
</template>
<script setup>
import { useField, useForm } from 'vee-validate';
const { handleSubmit } = useForm();
const onSubmit = handleSubmit(values => {
alert(JSON.stringify(values, null, 2));
});
const { value: twitter } = useField('[links.twitter]');
const { value: github } = useField('[links.github]');
</script>
Submitting the previous form would result in the following values being passed to your handler:
js{
"links.twitter": "https://twitter.com/logaretm",
"links.github": "https://github.com/logaretm"
}
Field Arrays v4.5
Field arrays are a special type of nested array fields, they are often used to collect repeatable pieces of data or repeatable forms. They are often called “repeatable fields”.
Unlike the components API, it can be tricky to set up a group of repeatable fields with the composition API in the same component. This is because you usually need an input component to iterate over.
The following snippet uses the Field
component as the input component, but you can use any component as long as they call useField
internally.
To set up a repeatable field, you can use useFieldArray
to help you manage the array values and operations:
vue<template>
<form @submit="onSubmit" novalidate>
<div v-for="(field, idx) in fields" :key="field.key">
<Field :name="`links[${idx}]`" type="url" />
<button type="button" @click="remove(idx)">Remove</button>
</div>
<button type="button" @click="push('')">Add</button>
<button>Submit</button>
</form>
</template>
<script setup>
import { Field, useForm, useFieldArray } from 'vee-validate';
const { handleSubmit } = useForm({
initialValues: {
links: ['https://github.com/logaretm'],
},
});
const { remove, push, fields } = useFieldArray('links');
const onSubmit = handleSubmit(values => {
console.log(JSON.stringify(values, null, 2));
});
</script>
Field Array Paths
When planning to use useFieldArray
you need to provide a name
prop which is the path of the array starting from the root form value, you can use dot notation for object paths or indices for array paths.
Here are a few examples:
Iterate over the users
array:
jsconst { remove, push, fields } = useFieldArray('users');
Iterate over the domains
inside settings.dns
object:
jsconst { remove, push, fields } = useFieldArray('settings.dns.domains');
Iteration Keys
The FieldArrayEntry
item exposes a key
property, this property is unique and is auto-generated for you so you can use it as an iteration key.
vue<template>
<form @submit="onSubmit" novalidate>
<div v-for="(field, idx) in fields" :key="field.key">
<Field :name="`links[${idx}]`" type="url" />
</div>
</form>
</template>
<script setup>
import { Field, useForm, useFieldArray } from 'vee-validate';
const { handleSubmit } = useForm({
initialValues: {
links: ['https://github.com/logaretm'],
},
});
const { fields } = useFieldArray('links');
</script>
This auto-generated key
property is very convenient as you no longer have to provide your own unique key for each item.
Array Helpers
The <useFieldArray />
function provides the following properties and functions:
fields
: a read-only version of your array field items, it includes some useful properties likekey
,isFirst
andisLast
, the actual item value is inside.value
property. You should use it to iterate withv-for
.push(item: any)
: adds an item to the end of the array.prepend(item: any)
: adds an item to the start of the array.insert(idx: number, item: any)
: Inserts an array item at the specified index.remove(idx: number)
: removes the item with the given index from the array.swap(idxA: number, idxB: number)
: Swaps two array elements by their indexes.replace(items: any[])
: Replaces the entire array values with the given items.update(idx: number, value: any)
: Updates an array item value at the specified index.move(oldIdx: number, newIdx: number)
: Moves an array item to a different position within the array.
Read the API reference for more information.
Caveats
Paths creation and destruction
vee-validate creates the paths inside the form data automatically but lazily, so initially, your form values won’t contain the values of the fields unless you provide initial values for them. It might be worthwhile to provide initial data for your forms with nested paths.
When fields get unmounted like in the case of conditional rendered fields with v-if
or v-for
, their path will be destroyed just as it was created if they are the last field in that path. So you need to be careful while accessing the nested field in values
inside your submission handler.
Path destruction can be annoying when dealing with multi-step forms or tabbed forms where you want all the values to be available even when the fields are unmounted. You can control this behavior by passing keepValueOnUnmount
prop to the useField
function or you can do it for all the fields by passing keepValuesOnUnmount
to the useForm
function.
Note that the priority of this configuration follows the field config first then it fallbacks to the form’s config.
jsimport { useForm } from 'vee-validate';
// keep all values when their fields get unmounted
const { values } = useForm({
keepValuesOnUnmount: true,
});
jsimport { useField } from 'vee-validate';
// this field value will be removed
const field = useField('field', undefined, {
keepValueOnUnmount: false,
});
Referencing Errors
When referencing errors using errors
object returned from the useForm
function. Make sure to reference the field name in the same way you set it on the name
argument for that field. So even if you avoid nesting you should always include the square brackets. In other words errors
do not get nested, they are always flat.
Nested Fields With Validation Schema
Since vee-validate supports form-level validation, referencing the nested fields may vary depending on how you are specifying the schema.
If you are using yup, you can utilize the nested yup.object
or yup.array
schemas to provide validation for your nested fields, here is a quick example:
vue<template>
<form @submit="onSubmit">
<input v-model="name" />
<span>{{ errors['user.name'] }}</span>
<input v-model="address" />
<span>{{ errors['user.addresses[0]'] }}</span>
<button>Submit</button>
</form>
</template>
<script setup>
import { useField, useForm } from 'vee-validate';
import * as yup from 'yup';
const { handleSubmit, errors } = useForm({
validationSchema: yup.object({
user: yup.object({
name: yup.string().required(),
addresses: yup.array().of(yup.string().required()),
}),
}),
});
const { value: name } = useField('user.name');
const { value: address } = useField('user.addresses[0]');
const onSubmit = handleSubmit(values => {
alert(JSON.stringify(values, null, 2));
});
</script>
You can visit this link for a practical example using nested arrays.