VeeValidate

new

Forms that check their own homework. VeeValidate and Zod on top of kappa-ui's Field components.

Source

VeeValidate is the long-standing form library for Vue. It keeps the values, errors and touched state, and validates them against a schema; here that's a Zod schema. kappa-ui has no form component of its own: VeeValidate holds the state, and the Field components lay the form out and wire its labels, descriptions and errors.

Demo

Bug report

Help us improve by reporting what went wrong.

0/100 characters. Include the steps.

Installation

pnpm add vee-validate zod

VeeValidate 4 doesn't understand Zod 4. Hand it a Zod 4 schema as it is and every value passes, without a word. @vee-validate/zod, the official bridge, expects Zod 3 and throws on a failing union. kappa-ui ships a small adapter instead: toTypedSchema turns any Standard Schema into the schema VeeValidate reads. Zod 4, Valibot and ArkType are all Standard Schemas.

The examples on this page list vee-validate, zod and the adapter, so adding one of them with the CLI installs all three.

Usage

<script setup lang="ts">
import { useForm } from 'vee-validate'
import { useTemplateRef } from 'vue'
import * as z from 'zod'

import { Field, FieldError, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { focusFirstInvalid } from '@/lib/field-context'
import { toTypedSchema } from '@/lib/standard-schema'

const Signup = z.object({
  email: z.email('Enter a valid email address.'),
})

const { defineField, errors, handleSubmit } = useForm({
  validationSchema: toTypedSchema(Signup),
  initialValues: { email: '' },
})

const [email, emailAttrs] = defineField('email')

const form = useTemplateRef('form')
const submit = handleSubmit(save, () => focusFirstInvalid(form.value))
</script>

<template>
  <form ref="form" novalidate @submit="submit">
    <Field :invalid="!!errors.email" required>
      <FieldLabel>Email</FieldLabel>
      <Input v-model="email" v-bind="emailAttrs" type="email" />
      <FieldError :errors="errors.email" />
    </Field>
  </form>
</template>

VeeValidate has a Field component too. When you use it, import it as VeeField and keep kappa-ui's under its own name.

  • useForm creates the form from the schema and the starting values. errors holds the first message of every invalid field, by path.
  • defineField returns the field's value, for v-model, and attributes that tell VeeValidate when the field blurs.
  • handleSubmit stops the page reload, validates, and calls your handler only with valid data, typed from the schema's output. Its second argument runs when the data isn't valid.
  • novalidate is required. required on Field puts the native required on the control, and without novalidate the browser's own bubbles block the submit before VeeValidate sees it.
  • kappa-ui's Field takes invalid and passes it on. The control inside gets aria-invalid, is described by the error, and turns --destructive; the label turns with it. Don't set aria-invalid on the control yourself.

Validation timing

VeeValidate checks a field when the value changes and when the field blurs. That's fine for a select, but a text field complains from the first keystroke. Pass a function to defineField to wait for the blur, then check every keystroke once the field is wrong:

const lazy = (state: { errors: string[] }) => ({ validateOnModelUpdate: state.errors.length > 0 })
const [title, titleAttrs] = defineField('title', lazy)
OptionChecks the fieldDefault
validateOnModelUpdatewhen v-model changestrue
validateOnBlurwhen the attributes see a blurtrue
validateOnChangewhen the attributes see a change eventtrue
validateOnInputwhen the attributes see an input eventfalse

Controls

Every control takes its value with v-model. Text controls, Input and Textarea, also take v-bind with the field's attributes, so they validate on blur. The attributes only tell VeeValidate that something happened, they never read the event's value, so they never corrupt a value. The other controls take v-model alone and validate when their value changes.

A select or combobox validates when a value is picked. Don't move the blur to the trigger: it blurs as soon as the list takes focus, and the error would flash while the user is still choosing.

Select

Used for emails and the interface.

For a group of checkboxes or radios, put invalid on the FieldSet and name the group with FieldLegend. A FieldLabel would point at nothing, since the group has no single control. A switch that has to be on is z.boolean().refine(...).

Choices
Notifications
Plan

For individuals.

For small teams.

Ask for a code from your phone when you sign in.

InputNumber keeps a number, TagsInput and PinInput keep arrays, and a range slider keeps two numbers. Zod can turn them into whatever you send: here the six digits of the code become one string with transform.

Controls

Press Enter after each address.

$20 – $100

The Field component

VeeValidate's own Form and Field components do the same through a slot. Form renders a <form novalidate> and runs @submit with valid data and @invalid-submit without. Field hands its slot the value and the handlers. Bind them like this:

ControlBinding
Input, Textarea, InputFloating, InputGroupInputv-bind="componentField"
Every other control:model-value="value" @update:model-value="handleChange"
Blur, where you want it@blur="handleBlur" on the text input itself

Never use componentField on the other controls. It listens for input and change events on the control's root and reads the value from the event. Reka UI's controls fire those from their inner and hidden inputs, so the value turns into text: a number becomes "42", a tags input gets the typed draft, a combobox gets the search text. Never bind field either: it sets the native value attribute, and the control's empty v-model wipes the starting value.

Field slot

Children count as guests.

Submitting and focus

Pass the form to focusFirstInvalid in the invalid handler. It waits for the errors to render, then focuses the first invalid control in the page's order, not the schema's: the input, the select trigger, the slider thumb, or the box Tab would reach in a group. A screen reader then reads the label, the invalid state and the error.

const submit = handleSubmit(save, () => focusFirstInvalid(form.value))

isSubmitting is true while an async handler runs. Disable the submit button and show a Spinner in it, but leave the fields alone: focus can't move to a disabled field.

<Button type="submit" :disabled="isSubmitting">
  <Spinner v-if="isSubmitting" />
  {{ isSubmitting ? 'Inviting' : 'Invite' }}
</Button>

Errors from the server go in with setFieldError, or setErrors for several, and show up in the same FieldError. Move focus to them too:

const submit = handleSubmit(async (invite) => {
  const response = await send(invite)
  if (response.taken) {
    setFieldError('email', 'This email is already a member.')
    await focusFirstInvalid(form.value)
  }
})

Components deeper in the form read its state with useFormContext, useIsSubmitting, useIsFormDirty and friends, without passing props down.

Arrays

useFieldArray lists the items of an array field, with a stable key for each, and push, remove, insert, move and swap change them. Bind each item with VeeValidate's Field and a path such as :name="`emails[${index}].address`". The array's own errors, such as a minimum or maximum length, sit at its path: errors.emails.

Array
Email addresses

Add up to 5 addresses where we can reach you.

Dialogs

Closing a dialog moves focus back to the button that opened it. To the field that had focus, that's a blur, and VeeValidate would validate it while the dialog fades out. Turn the blur and change checks off for fields in a dialog: they're checked on submit, then on every keystroke once wrong.

const quiet = (state: { errors: string[] }) => ({
  validateOnBlur: false,
  validateOnChange: false,
  validateOnModelUpdate: state.errors.length > 0,
})
const [email, emailAttrs] = defineField('email', quiet)
Dialog

Resetting

resetForm() returns every field to its starting value and clears the errors and touched state. The select shows its placeholder again. Pass values to reset to new ones, for example after saving:

resetForm({ values: saved })

API Reference

toTypedSchema

From @/lib/standard-schema.

ArgumentTypeDescription
schemaStandardSchemaV1A Zod 4, Valibot, ArkType or other Standard Schema.

Returns a TypedSchema for useForm({ validationSchema }) or <Form :validation-schema>. Its input and output types come from the schema. Each issue lands at its field's path, emails[0].address; a field with several issues keeps all of them, in order.

focusFirstInvalid

From @/lib/field-context, which every form control already installs.

ArgumentTypeDescription
rootParentNode | null | undefinedWhere to look, usually the form.
optionsFocusOptionsPassed to focus(). focusVisible defaults to true.

Returns a promise of the focused element, or null when no invalid control took focus. A control that can't take focus, such as one in a hidden tab, is skipped for the next one. It works with any validation, not only VeeValidate.

Accessibility

Field does the wiring: the label points at the control, and the control is described by its description and error, and marked aria-invalid, while each one renders. Errors aren't announced as they appear: on submit, focus moves to the first invalid control, and its error is read out with it. Reka UI's hidden native inputs stay out of the tab order and the accessibility tree.

KeyAction
Tab / Shift + TabMoves through the controls in page order. With the lazy timing, leaving a text field checks it.
EnterIn a text field, submits the form; with errors, focus moves to the first invalid control. In a tags input with typed text, adds the tag instead.
SpaceToggles a checkbox or switch, which checks the field.
Arrow keysPick a radio or move a slider thumb, which checks the field.
EscapeCloses a dialog form without checking its fields.

Known limits

  • componentField corrupts the value of Reka UI based controls: their inner inputs fire input and change events that VeeValidate reads (reka-ui#1653, reka-ui#2241). Use v-model, or the binding table above.
  • A dialog, drawer or menu that closes blurs the field that had focus, which validates it (reka-ui#2630, shadcn-vue#1687). Turn off the blur and change checks in a dialog, as shown above.
  • A select never reports a blur, and the user can't pick "nothing" from its list (reka-ui#2564). It validates on change, and resetForm() brings the placeholder back.
  • Before reka-ui 2.11, a tags input cancels its Enter a tick late, and some browsers could submit the form while adding a tag (reka-ui#2966). kappa-ui's TagsInputInput holds that submit back on 2.10; 2.11 fixes it in Reka UI.
  • VeeValidate 4 reads neither Zod 4 nor Standard Schema, and @vee-validate/zod throws on Zod 4 unions (vee-validate#5151, vee-validate#5085). Hence the adapter. VeeValidate 5, in beta, reads Standard Schemas itself.
  • Some browsers ignore the focusVisible option of focus(). There, a select trigger or a checkbox focused after a mouse click on Submit shows no ring, since the browser decides the click wasn't keyboard use. Text fields always show it.

Changelog

  1. registry 0.13.0

    d71e3ef — Forms with VeeValidate and Zod. New standard-schema lib item with toTypedSchema, which lets VeeValidate 4 validate with Zod 4, Valibot or any other Standard Schema: VeeValidate 4 passes a raw Zod 4 schema without a single error, and @vee-validate/zod throws on Zod 4 unions. Each issue lands at its field's path, such as emails[0].address. New examples bind every kind of control: a bug report, a select and combobox, choice groups, number, tags, pin and range inputs, a field array, an invite dialog with an error from the server, and VeeValidate's own Form and Field components through the slot.

    lib/field-context exports focusFirstInvalid(root), which moves focus to the first invalid control in page order once the errors have rendered: the input, the select trigger, the slider thumb, or the box Tab would reach in a checkbox or radio group. A control that can't take focus, such as one in a hidden tab, is skipped. It works with any validation.

    TagsInputInput no longer lets the form submit when Enter adds a tag on reka-ui 2.10, which cancels that Enter a tick late (unovue/reka-ui#2966). On reka-ui 2.11 nothing changes.