### prepend method example
Source: https://vee-validate.logaretm.com/v4/api/use-field-array
Adds an item to the start of the array. Get the prepend function from the composable and call it within a custom function.
```javascript
// get prepend function from composable in component setup
const { prepend } = useFieldArray('links');
// call prepend function within custom function
const myPrependFunction = () => {
// adds a new item to the array
prepend({ url: '' });
};
```
--------------------------------
### Install Vue CLI
Source: https://vee-validate.logaretm.com/v4/tutorials/basics
Installs the latest Vue CLI globally to prepare a Vue 3.x project.
```sh
npm install -g @vue/cli@next
```
--------------------------------
### Incorrect: Returning Composable Objects from setup
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/caveats
Demonstrates that returning the composable objects directly from setup does not work in templates because setup does not recursively expose refs inside these objects. The template comments show which usages fail.
```vue
{{ form.meta.valid }}
```
--------------------------------
### Install @vee-validate/rules
Source: https://vee-validate.logaretm.com/v4/guide/global-validators
Install the @vee-validate/rules package using yarn or npm.
```sh
shyarn add @vee-validate/rules
# or with npm
npm install @vee-validate/rules
```
--------------------------------
### push method example
Source: https://vee-validate.logaretm.com/v4/api/use-field-array
Adds an item to the end of the array. Get the push function from the composable and call it within a custom function.
```javascript
// get push function from composable in component setup
const { push } = useFieldArray('links');
// call push function within custom function
const myPushFunction = () => {
// adds a new item to the array
push({ url: '' });
};
```
--------------------------------
### Install vee-validate with package manager
Source: https://vee-validate.logaretm.com/v4/guide/overview
Install vee-validate using yarn, npm, or pnpm. Choose one command based on your package manager.
```bash
yarn add vee-validate
# or
npm i vee-validate --save
# or
pnpm add vee-validate
```
--------------------------------
### Dynamic configuration example
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/getting-started
Shows how to pass a function to `defineField` for dynamic configuration. The example makes validation 'eager': if the field has no errors, it validates on `change`; once invalid, it validates on each input event.
```ts
const { defineField } = useForm({
// ...
});
const [email, emailProps] = defineField('email', {
props: state => ({ error: state.errors[0] })
});
```
--------------------------------
### Install @vee-validate/nuxt with npm, pnpm, or yarn
Source: https://vee-validate.logaretm.com/v4/integrations/nuxt
Install the module using your preferred package manager. The commands are shown for npm, pnpm, and yarn.
```sh
sh# npm
npm i @vee-validate/nuxt
# pnpm
pnpm add @vee-validate/nuxt
# yarn
yarn add @vee-validate/nuxt
```
--------------------------------
### Install @vee-validate/zod and @vee-validate/valibot
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/custom-inputs
Install the integration packages for Zod and Valibot with npm, pnpm, or yarn. Required before using toTypedSchema with either library.
```sh
sh# with npm
npm i @vee-validate/zod
# with pnpm
pnpm add @vee-validate/zod
# with yarn
yarn add @vee-validate/zod
```
```sh
sh# with npm
npm i @vee-validate/valibot
# with pnpm
pnpm add @vee-validate/valibot
# with yarn
yarn add @vee-validate/valibot
```
--------------------------------
### Install @vee-validate/i18n
Source: https://vee-validate.logaretm.com/v4/guide/i18n
Install the @vee-validate/i18n package using either Yarn or npm.
```sh
yarn add @vee-validate/i18n
# or with npm
npm install @vee-validate/i18n
```
--------------------------------
### Type-safe useForm with generic type and usage examples
Source: https://vee-validate.logaretm.com/v4/api/use-form
Shows how to use the generic type to get auto-complete and type checking for errors and field values.
```TypeScript
import { useForm } from 'vee-validate';
interface LoginForm {
email: string;
password: string;
}
// in your setup
const { errors, setErrors, setFieldValue } = useForm();
errors.value; // typed as { email?: string; password?: string }
setErrors({
email: 'This field is invalid', // auto-complete for `email` and `password`
});
setFieldValue('email', 'example@gmail.com'); // auto-complete for the field name and its value type
```
--------------------------------
### Install @vee-validate/valibot
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/getting-started
Install the @vee-validate/valibot package using npm, pnpm, or yarn to use Valibot schemas with vee-validate.
```sh
# with npm
npm i @vee-validate/valibot
# with pnpm
pnpm add @vee-validate/valibot
# with yarn
yarn add @vee-validate/valibot
```
--------------------------------
### Define yup schema in setup to avoid reactivity
Source: https://vee-validate.logaretm.com/v4/guide/best-practices
Define the `yup` schema in `setup()` to keep it non-reactive, avoiding deep reactive conversion overhead. This is recommended for large schemas.
```js
{
setup() {
// Non-reactive because it was not explicitly defined with `reactive` or `ref`
const schema = yup.object({
email: yup.string().required().email(),
password: yup.string().required().min(8),
});
return {
schema,
};
},
}
```
--------------------------------
### Custom input component with useField and InputText
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/custom-inputs
Contrasts the imperative approach with useForm/defineField against the declarative useField approach in a custom input component. The useField example shows the required props setup and the v-model binding to the returned value.
```javascript
const { defineField } = useForm();
const email = defineField('email');
const firstName = defineField('firstName');
const lastName = defineField('lastName');
const password = defineField('password');
const passwordConfirm = defineField('passwordConfirm');
```
```vue
{{ errorMessage }}
```
--------------------------------
### Field array path for users array
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/nested-objects-and-arrays
Use useFieldArray with a path to iterate over the 'users' array. The example shows the same setup as the previous snippet.
```javascript
const { remove, push, fields } = useFieldArray('users');
```
--------------------------------
### replace method example
Source: https://vee-validate.logaretm.com/v4/api/use-field-array
Replaces the entire array of fields. Get the replace function from the composable and call it within a custom function.
```javascript
// get replace function from composable in component setup
const { replace } = useFieldArray('links');
// call replace function within custom function
const myReplaceFunction = () => {
// replace the entire array with these items
replace([{ url: 'https://google.com' }, { url: 'https://vuejs.org' }]);
};
```
--------------------------------
### move method example
Source: https://vee-validate.logaretm.com/v4/api/use-field-array
Moves an array item to a different position within the array. Get the move function from the composable and call it within a custom function.
```javascript
// get move function from composable in component setup
const { move } = useFieldArray('links');
// call move function within custom function
const myMoveFunction = () => {
// move array item to a different position
move(2, 1);
};
```
--------------------------------
### Install @vee-validate/zod
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/getting-started
Install the @vee-validate/zod package using npm, pnpm, or yarn to use Zod schemas with vee-validate.
```sh
# with npm
npm i @vee-validate/zod
# with pnpm
pnpm add @vee-validate/zod
# with yarn
yarn add @vee-validate/zod
```
--------------------------------
### Install @vee-validate/yup
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/getting-started
Install the @vee-validate/yup package using npm, pnpm, or yarn to enable better support and TypeScript inference for Yup schemas.
```sh
# with npm
npm i @vee-validate/yup
# with pnpm
pnpm add @vee-validate/yup
# with yarn
yarn add @vee-validate/yup
```
--------------------------------
### Currency Input Example - Display vs Actual Value
Source: https://vee-validate.logaretm.com/v4/examples/value-formatting
Shows the contrast between a hard-to-read number and a formatted version with thousand separators, illustrating why masks are used.
```text
sh# hard to read
10000000
# Much easier
10,000,000
```
--------------------------------
### Install vee-validate, zod, and @vee-validate/zod
Source: https://vee-validate.logaretm.com/v4/integrations/zod-schema-validation
Install the required packages using yarn, npm, or pnpm. The package @vee-validate/zod provides the toTypedSchema function to convert Zod schemas for use with vee-validate.
```shell
yarn add vee-validate zod @vee-validate/zod
# or with NPM
npm install vee-validate zod @vee-validate/zod
# or with Pnpm
pnpm add vee-validate zod @vee-validate/zod
```
--------------------------------
### swap method example
Source: https://vee-validate.logaretm.com/v4/api/use-field-array
Swaps the items at the given indexes with each other. Both indexes must exist in the array or it won't have an effect.
```javascript
// get swap function from composable in component setup
const { swap } = useFieldArray('links');
// call swap function within custom function
const mySwapFunction = () => {
// Swaps the 4th item with the 5th
swap(3, 4);
};
```
--------------------------------
### setValues example
Source: https://vee-validate.logaretm.com/v4/api/use-form
Sets multiple field values at once. Triggers validation for the changed fields.
```javascript
const { setValues } = useForm();
setValues({
email: 'example@gmail.com',
password: 'p@a$$W0rD',
});
```
--------------------------------
### Set initial values with useForm
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/handling-forms
Sets initial values for fields using the `initialValues` option. By default, fields start with `undefined`.
```js
const { defineInputBinds } = useForm({
initialValues: {
email: 'test@example.com',
password: 'p@$$w0rd',
},
});
```
--------------------------------
### Full example with CustomInput.vue
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/getting-started
Complete example showing a form with a custom input component that receives an `error` prop. The `defineField` maps the first error to the `error` prop. The template binds the field value and props to the custom input.
```vue
values: {{ values }}
errors: {{ errors }}
```
--------------------------------
### Clean App.vue
Source: https://vee-validate.logaretm.com/v4/tutorials/basics
Cleanup contents of App.vue to start with an empty Vue component.
```vue
```
--------------------------------
### Configure @vee-validate/nuxt with array syntax
Source: https://vee-validate.logaretm.com/v4/integrations/nuxt
Use the array syntax in `modules` to pass options. This example enables auto imports and customizes component names.
```ts
tsexport default defineNuxtConfig({
// ...
modules: [
//...
[
'@vee-validate/nuxt',
{
// disable or enable auto imports
autoImports: true,
// Use different names for components
componentNames: {
Form: 'VeeForm',
Field: 'VeeField',
FieldArray: 'VeeFieldArray',
ErrorMessage: 'VeeErrorMessage',
},
},
],
],
});
```
--------------------------------
### Use community locale files
Source: https://vee-validate.logaretm.com/v4/guide/i18n
Imports pre-translated locale files for English and Arabic and passes them to localize to get messages for all global rules.
```js
import { configure } from 'vee-validate';
import { localize } from '@vee-validate/i18n';
import en from '@vee-validate/i18n/dist/locale/en.json';
import ar from '@vee-validate/i18n/dist/locale/ar.json';
configure({
generateMessage: localize({
en,
ar,
}),
});
```
--------------------------------
### handleSubmit with FormActions example
Source: https://vee-validate.logaretm.com/v4/api/use-form
Shows how to use the FormActions object passed as the second argument to the submit callback. Provides methods like setFieldValue, setValues, setFieldError, setErrors, and resetForm.
```javascript
const { handleSubmit } = useForm();
const onSubmit = handleSubmit((values, actions) => {
// Send data to API
alert(JSON.stringify(values, null, 2));
// the form object contains useful methods
// set a single field value
actions.setFieldValue('field', 'hello');
// set multiple fields values
actions.setValues({ email: 'value', password: 'hi' });
// set a single field error
actions.setFieldError('field', 'this field is bad');
// set multiple fields errors
actions.setErrors({ email: 'bad email', password: 'bad password' });
// reset the form
actions.resetForm();
});
```
--------------------------------
### Install vee-validate
Source: https://vee-validate.logaretm.com/v4/tutorials/basics
Adds vee-validate to the project using either Yarn or npm. The npm command includes the --save flag.
```sh
yarn add vee-validate
# or
npm install vee-validate --save
```
--------------------------------
### insert method example
Source: https://vee-validate.logaretm.com/v4/api/use-field-array
Adds an item at the specified index. If the index is out of bounds (larger than length) the operation is ignored; you can still add items as the last item.
```javascript
// get insert function from composable in component setup
const { insert } = useFieldArray('links');
// call insert function within custom function
const myInsertFunction = () => {
// inserts a new item to the array at the second index
insert(1, { url: '' });
};
```
--------------------------------
### prepend
Source: https://vee-validate.logaretm.com/v4/api/use-field-array
Documents the prepend method of the field array context, which adds an item to the start of the array.
```APIDOC
## prepend(item: any)
### Description
Adds an item to the start of the array.
### Method
Function
### Endpoint
prepend
### Parameters
#### Request Body
- **item** (any) - Required - The item to add to the start of the array.
### Example
```js
const { prepend } = useFieldArray('links');
prepend({ url: '' });
```
```
--------------------------------
### validate example
Source: https://vee-validate.logaretm.com/v4/api/use-form
Validates all fields and populates the errors object. Returns a promise resolving to an object with aggregated validation results.
```javascript
const { validate } = useForm();
const { valid, errors } = await validate();
```
--------------------------------
### setTouched example
Source: https://vee-validate.logaretm.com/v4/api/use-form
Sets multiple fields' touched meta flags. Does not trigger validation.
```javascript
const { setTouched } = useForm();
setTouched({
email: true,
password: false,
});
```
--------------------------------
### String expression example
Source: https://vee-validate.logaretm.com/v4/guide/global-validators
A string expression for a validation rule, using the pipe-separated format.
```js
js'required|between:0,10';
```
--------------------------------
### Nested FieldArray for users and links
Source: https://vee-validate.logaretm.com/v4/guide/components/nested-objects-and-arrays
Nested FieldArray example that iterates over both users and their links arrays, using dot notation and indices to build field names.
```vue
vue
```
--------------------------------
### Use minLength rule on a Field component
Source: https://vee-validate.logaretm.com/v4/guide/global-validators
Shows how to apply the `minLength` rule with an argument (`8`) on a `Field` component. The colon `:` starts the arguments, and the value is passed as a string.
```vue
```
--------------------------------
### Object expression example
Source: https://vee-validate.logaretm.com/v4/guide/global-validators
The same validation rule expressed as an object, which is more expressive and less limited by the string format.
```js
js{ required: true, between: [0, 10] }
```
--------------------------------
### handleSubmit basic example
Source: https://vee-validate.logaretm.com/v4/api/use-form
Creates a submit event handler that prevents default form submission and stops propagation. The callback runs after validation passes and receives the form values.
```vue
```
--------------------------------
### ErrorMessage Component
Source: https://vee-validate.logaretm.com/v4/api/error-message
Documentation for the ErrorMessage component, including its props, slots, usage examples, and caveats.
```APIDOC
## [Component] ErrorMessage
### Description
Displays error messages for a specific field without using scoped slots on Form or Field components. Renders nothing when there are no messages for the associated field.
### Props
| Prop | Type | Required/Default | Description |
|------|------|------------------|-------------|
| `as` | `string` | `"span"` | The element to render as a root node |
| `name` | `string` | Required | The field's name to display messages for |
### Slots
#### default
| Scoped Prop | Type | Description |
|-------------|------|-------------|
| `message` | `string` | The element's error message |
### Usage Example
```vue
```
### Rendering Messages
- Use the `as` prop to control the root node (default: `span`).
- Use the default scoped slot for flexible markup and multiple root nodes.
- If no `as` prop is provided while using a slot, only the slot contents are rendered (renderless).
- When there are no error messages, the component renders nothing.
### Caveats
- Must be used inside a `Form` component.
- Can only display errors for a field within the same form.
```
--------------------------------
### Access fields from useFieldArray
Source: https://vee-validate.logaretm.com/v4/api/use-field-array
Call the composable in component setup to get a readable version of the links array.
```javascript
// call composable in component setup to get readable version of links array
const { fields } = useFieldArray('links');
```
--------------------------------
### defineField usage with native inputs
Source: https://vee-validate.logaretm.com/v4/api/use-form
Returns a model and props/attributes pair for a field. Must be called in the setup function. Accepts root or nested paths with dot notation. Works with native HTML inputs.
```vue
{{ errors.email }}{{ errors.password }}
```
--------------------------------
### Set up useFieldArray
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/nested-objects-and-arrays
Import useForm and useFieldArray, call useForm to create a form context, then use useFieldArray to manage an array field named 'users'. The returned helpers include remove, push, and fields.
```javascript
import { useForm, useFieldArray } from 'vee-validate';
useForm();
const { remove, push, fields } = useFieldArray('users');
```
--------------------------------
### FieldArray path example: iterate users array
Source: https://vee-validate.logaretm.com/v4/guide/components/nested-objects-and-arrays
Iterates over a top-level array named users, using entry.key as the iteration key and indexing into the array with links[${idx}].name for the field name.
```vue
vue
```
--------------------------------
### Load locale from CDN with loadLocaleFromURL
Source: https://vee-validate.logaretm.com/v4/guide/i18n
Loads a locale file from a CDN URL when using Vue.js over CDN. Includes the necessary script tags, installs all rules, downloads and merges the Arabic locale from the given URL, and activates it via configure with localize('ar').
```html
```
--------------------------------
### FieldArray path example: iterate settings.dns.domains
Source: https://vee-validate.logaretm.com/v4/guide/components/nested-objects-and-arrays
Iterates over an array nested inside an object path using dot notation in the FieldArray name and template literal for the field name.
```vue
vue
```
--------------------------------
### validate() usage
Source: https://vee-validate.logaretm.com/v4/api/field
Validates the field's current value and returns a promise with error messages. The example creates a field with a required rule and triggers validation.
```js
const { validate } = useField('field', value => !!value);
// trigger validation
await validate();
```
--------------------------------
### Custom component with modelValue events
Source: https://vee-validate.logaretm.com/v4/guide/components/validation
For custom components, listen to the proper events when using v-bind. This example uses modelValue and update:modelValue events.
```vue
```
--------------------------------
### remove method example
Source: https://vee-validate.logaretm.com/v4/api/use-field-array
Removes the item at the specified index from the array if it exists. Get the remove function from the composable and call it within a custom function.
```javascript
// get remove function from composable in component setup
const { remove } = useFieldArray('links');
// call remove function within custom function
const myRemoveFunction = () => {
// removes the second item from the array
remove(1);
};
```
--------------------------------
### App.vue: Setup form with Yup schema and submit handlers
Source: https://vee-validate.logaretm.com/v4/examples/custom-inputs
Sets up a vee-validate Form with a Yup validation schema. The onSubmit handler alerts the form values as JSON, and onInvalidSubmit adds a temporary 'invalid' class to the submit button. Requires the 'vee-validate' and 'yup' packages.
```vue
```
--------------------------------
### defineField
Source: https://vee-validate.logaretm.com/v4/api/use-form
Returns a model and a props/attributes pair for a specified field. Must be called in the setup function. Accepts a single field path, supporting nested paths with dot notation. Can be used with native inputs and custom components, with optional configuration for validation behavior.
```APIDOC
## defineField
### Description
Returns a model and a props/attributes pair for the specified field. Must be called in the `setup` function. Accepts a single field path, supporting nested paths with dot notation. Works with native inputs and custom components.
### Parameters
- **field** (string) - Required - The field path. Can be a root field path or a nested path using dot notation (e.g., `some.user.path`).
- **config** (object | function) - Optional - Configuration object or a function that returns a configuration object based on the field state.
### Configuration Object
- **props** (function | object) - Optional - A getter function that receives the current field state and returns additional props to bind to the component. When using a function configuration, this is a plain object.
- **label** (string) - Optional - A label for the field, only used with global validation rules.
- **validateOnBlur** (boolean) - Optional - Validates when `blur` event is emitted from the element/component.
- **validateOnChange** (boolean) - Optional - Validates when `change` event is emitted from the element/component.
- **validateOnInput** (boolean) - Optional - Validates when `input` event is emitted from the element/component.
- **validateOnModelUpdate** (boolean) - Optional - Validates when the returned model value changes.
### Returns
- **model** - A ref to be used with `v-model`.
- **props** - An object of attributes to bind to the element/component.
### Example (Basic)
```vue
{{ errors.email }}{{ errors.password }}
```
### Example (With Configuration)
```ts
const [field, props] = defineField('field', {
// A getter that computes and adds any additional props to the component
// It receives the current field state as an argument
props(state) {
// This is just an example, by default this is an empty object
return {
'aria-invalid': state.errors.length > 0 ? 'true' : 'false',
};
},
// A label for the field, only used with global validation rules
label: 'a label',
// Validates when `blur` event is emitted from the element/component
validateOnBlur: true,
// Validates when `change` event is emitted from the element/component
validateOnChange: true,
// Validates when `input` event is emitted from the element/component
validateOnInput: false,
// Validates when the returned model value changes
validateOnModelUpdate: true,
});
```
### Example (Lazy Configuration)
```ts
const [field, props] = defineField('field', state => {
return {
// A getter that computes and adds any additional props to the component
props: {
// This is just an example, by default this is an empty object
'aria-invalid': state.errors.length > 0 ? 'true' : 'false',
},
// Validates when `blur` event is emitted from the element/component
validateOnBlur: true,
// Validates when `change` event is emitted from the element/component
validateOnChange: true,
// Validates when `input` event is emitted from the element/component
validateOnInput: false,
// Validates when the returned model value changes
validateOnModelUpdate: true,
};
});
```
```
--------------------------------
### Yup schema in data (reactive overhead)
Source: https://vee-validate.logaretm.com/v4/guide/best-practices
Defining a `yup` schema inside `data()` makes Vue deeply reactive, which is unnecessary overhead. Prefer `setup` or `markRaw` for large schemas.
```js
{
data() {
const schema = yup.object({
email: yup.string().required().email(),
password: yup.string().required().min(8),
});
return {
schema,
};
},
}
```
--------------------------------
### Basic usage of useFieldArray with push and remove
Source: https://vee-validate.logaretm.com/v4/api/use-field-array
Shows a Vue 3 component using useFieldArray to manage an array of links. The template renders fields with remove buttons and an add button, while the script setup initializes the form with initial values and defines the onSubmit handler.
```vue
```
--------------------------------
### defineInputBinds for native inputs
Source: https://vee-validate.logaretm.com/v4/api/use-form
Deprecated: use defineField instead. defineInputBinds creates a bindable object for a field path, intended for native HTML input elements. Must be called in setup.
```vue
{{ errors.email }}{{ errors.password }}
```
--------------------------------
### Create Vue 3 project with vue-cli
Source: https://vee-validate.logaretm.com/v4/tutorials/basics
Creates a new Vue project named 'vee-validate-tutorial' using the Vue CLI. Choose the Vue 3 template when prompted.
```sh
vue create vee-validate-tutorial
```
--------------------------------
### Create repeatable URL field with FieldArray
Source: https://vee-validate.logaretm.com/v4/guide/components/nested-objects-and-arrays
Example of a repeatable field using FieldArray with push and remove helpers. Requires being inside a Form or after calling useForm. Initial values show how to prefill the array.
```vue
vue
```
--------------------------------
### useField Options
Source: https://vee-validate.logaretm.com/v4/api/use-field
Shows how to pass additional options to the useField function and lists all available field options.
```APIDOC
## useField Options
### Description
Pass additional configuration options to the `useField` function to customize field behavior.
### Usage Example
```vue
{{ errorMessage }}
```
### Options
- `type`
- `label`
- `initialValue`
- `validateOnMount`
- `bails`
- `standalone`
- `validateOnValueUpdate`
- `keepValueOnUnmount`
- `syncVModel`
- `checkedValue` (checkbox/radio only)
- `uncheckedValue` (checkbox/radio only)
```
--------------------------------
### Vue template using resetForm to reset email value
Source: https://vee-validate.logaretm.com/v4/api/form
Shows how to use the resetForm slot prop to reset the form values, specifically setting the email field to 'example@example.com'. This changes the field's current and initial value, affecting future resets.
```vue
```
--------------------------------
### Import all of yup (avoid for bundle size)
Source: https://vee-validate.logaretm.com/v4/guide/best-practices
Imports the entire `yup` library, which increases bundle size. Avoid this in production; prefer named imports for tree-shaking.
```js
import * as yup from 'yup';
const schema = yup.object({
email: yup.string().email(),
// ...
});
```
--------------------------------
### Render a multi-select with 'as' prop and v-slot
Source: https://vee-validate.logaretm.com/v4/api/field
Example of a multi-select using the 'as' prop with 'multiple' and a v-slot to bind the selected state. Note that the Field component has partial support for native select[multiple] and does not set initial UI state; use v-model or bind selected attributes.
```vue
```
--------------------------------
### Basic validation example with vee-validate v4
Source: https://vee-validate.logaretm.com/v4/guide/components/validation
Complete basic validation example using vee-validate v4 with Vue 3. The HTML template uses VForm, VField, and ErrorMessage components; the JavaScript registers these components and defines an isRequired rule that returns an error message when the field is empty. The CSS styles the form elements. This example is from the CodePen 'Basic Example' by Abdelrahman Awad.
```html
```
```css
span {
display: block;
margin: 10px 0;
}
button, input {
display: block;
}
```
```javascript
const App = {
components: {
// Components were renamed to avoid conflicts of HTML form element without a vue compiler
VForm: VeeValidate.Form,
VField: VeeValidate.Field,
ErrorMessage: VeeValidate.ErrorMessage,
},
methods: {
isRequired(value) {
if (!value) {
return 'this field is required';
}
return true;
},
onSubmit(values) {
alert(JSON.stringify(values, null ,2));
}
}
}
Vue.createApp(App).mount('#app')
```
--------------------------------
### useForm(initialValues?: MaybeRef>)
Source: https://vee-validate.logaretm.com/v4/api/use-form
Sets the initial values for the form, can be a reactive object or reference.
```APIDOC
## useForm(initialValues?: MaybeRef>)
### Description
Sets the initial values for the form, can be a reactive object or reference.
### Parameters
#### initialValues?: MaybeRef>
- Type: MaybeRef>
- Optional
- The initial values for the form, can be a reactive object or reference.
### Example
```js
const { ... } = useForm({
initialValues: {
email: 'example@gmail.com',
password: 'p@$$w0rd',
}
});
```
```
--------------------------------
### Nested Array Submit Values
Source: https://vee-validate.logaretm.com/v4/guide/components/nested-objects-and-arrays
Expected values object passed to the submit handler for the nested array example above.
```js
{
"links": [
"https://twitter.com/logaretm",
"https://github.com/logaretm"
]
}
```
--------------------------------
### useForm with initialValues
Source: https://vee-validate.logaretm.com/v4/api/use-form
Sets the initial values for the form fields. The values can be a reactive object or reference.
```javascript
const { ... } = useForm({
initialValues: {
email: 'example@gmail.com',
password: 'p@$$w0rd',
}
});
```
--------------------------------
### Nested Object Submit Values
Source: https://vee-validate.logaretm.com/v4/guide/components/nested-objects-and-arrays
Expected values object passed to the submit handler for the nested object example above.
```js
{
"links": {
"twitter": "https://twitter.com/logaretm",
"github": "https://github.com/logaretm"
}
}
```
--------------------------------
### useForm with name
Source: https://vee-validate.logaretm.com/v4/api/use-form
Sets the form's name used in the devtools. Defaults to "Form".
```javascript
const { ... } = useForm({
name: 'LoginForm', // Defaults to "Form"
});
```
--------------------------------
### setFieldTouched example
Source: https://vee-validate.logaretm.com/v4/api/use-form
Sets a single field's touched meta flag. Setting it for a non-existing field has no effect.
```javascript
const { setFieldTouched } = useForm();
setFieldTouched('email', true);
```
--------------------------------
### useField errorMessage shortcut
Source: https://vee-validate.logaretm.com/v4/api/use-field
Get the first error via `errorMessage` computed ref; returns undefined if no errors.
```js
const { errorMessage } = useField('field', value => !!value);
errorMessage.value; // 'field is not valid' or undefined
```
--------------------------------
### useForm with generic type
Source: https://vee-validate.logaretm.com/v4/api/use-form
Provides a generic type to useForm to get strict type information for fields and their values.
```TypeScript
import { useForm } from 'vee-validate';
interface LoginForm {
email: string;
password: string;
}
// in your setup
const { errors } = useForm();
```
--------------------------------
### Define all rules globally
Source: https://vee-validate.logaretm.com/v4/guide/global-validators
Import the 'all' export and define every rule from @vee-validate/rules globally.
```js
jsimport { defineRule } from 'vee-validate';
import { all } from '@vee-validate/rules';
Object.entries(all).forEach(([name, rule]) => {
defineRule(name, rule);
});
```
--------------------------------
### validateField example
Source: https://vee-validate.logaretm.com/v4/api/use-form
Validates a specific field inside the form. Returns a promise resolving to an object with the validation result for that field.
```javascript
const { validateField } = useForm();
const { valid, errors } = await validateField('email');
```
--------------------------------
### Import only needed yup functions for tree-shaking
Source: https://vee-validate.logaretm.com/v4/guide/best-practices
Use named imports from `yup` to leverage tree-shaking and keep the bundle size minimal. This is the recommended approach.
```js
import { object, string } from 'yup';
const schema = object({
email: string().email(),
// ...
});
```
--------------------------------
### Get all error messages with errors ref
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/custom-inputs
Access all error messages for a field using the errors ref, which returns an array.
```js
jsconst { errors, value } = useField('fieldName', yup.string().required());
// contains an array of error messages, otherwise empty array
errors.value;
```
--------------------------------
### useForm with initialErrors
Source: https://vee-validate.logaretm.com/v4/api/use-form
Sets initial error messages for fields, useful for non-hydrated SSR applications like Laravel. Errors are applied on mounted.
```javascript
const { ... } = useForm({
initialErrors: {
email: 'This email is invalid',
password: 'Password too short',
}
});
```
--------------------------------
### setFieldValue example
Source: https://vee-validate.logaretm.com/v4/api/use-form
Sets a single field's value. If the field does not exist, it will not be reflected in the values ref. Triggers validation on the changed field.
```javascript
const { setFieldValue } = useForm();
setFieldValue('email', 'example@gmail.com');
```
--------------------------------
### Trigger validation with handleChange
Source: https://vee-validate.logaretm.com/v4/guide/composition-api/custom-inputs
Shows how to call handleChange with a value and optionally trigger validation. The second argument controls whether validation runs.
```js
const { handleChange } = useField('someField');
// validates by default
handleChange('new value');
// validates
handleChange('new value', true);
// Doesn't validate
handleChange('new value', false);
```
--------------------------------
### Basic Field component usage
Source: https://vee-validate.logaretm.com/v4/api/field
Renders a text input with the name 'field'. Requires importing Field from 'vee-validate' in a Vue 3 script setup.
```vue
```
--------------------------------
### Configure vee-validate with configure()
Source: https://vee-validate.logaretm.com/v4/api/configuration
Updates the global vee-validate configuration at runtime. Changes take effect for new Field and useField instances created afterwards.
```javascript
import { configure } from 'vee-validate';
configure({
bails: false,
});
```
--------------------------------
### Using DynamicForm with a basic schema in App.vue
Source: https://vee-validate.logaretm.com/v4/tutorials/dynamic-form-generator
Initial App.vue using the DynamicForm component with a schema. The schema defines three fields (name, email, password) each with label, name, and as properties. Demonstrates how to provide a schema to the DynamicForm component.
```vue
vue
```
--------------------------------
### handleSubmit.withControlled example
Source: https://vee-validate.logaretm.com/v4/api/use-form
Creates a submit handler that only submits fields controlled by useField or useFieldModel. Useful for virtual forms that may not use form elements.
```vue
```
--------------------------------
### update method example
Source: https://vee-validate.logaretm.com/v4/api/use-field-array
Updates the value at the specified index. Note that it doesn't merge values if they are objects. If the index is outside the array boundary the operation is ignored.
```javascript
// get update function from composable in component setup
const { update } = useFieldArray('links');
// call update function within custom function
const myUpdateFunction = () => {
// updates the 2nd item value
update(1, { url: '' });
};
```