Forms and validation in Vue

Intermediate · 14 min

Form state and validation from v-model and computed values, then handing the bookkeeping to VeeValidate with a Zod schema, plus FormKit's approach.

Before thisv-model on componentsComposables

Mohit Kumar Toshniwal · 14 min

Forms and validation in Vue

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Mohit Kumar ToshniwalReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A form is more state than it looks: each field has a value, an error, and a touched or dirty flag, and the form as a whole has validity and submitting state; hand-rolling that with refs and computeds works for small forms and gets repetitive fast.
  • Client-side validation is a user experience feature, never a security one; the server must validate the same rules again, and a good form shows server errors in the same place as client errors.
  • VeeValidate is a set of composables: useForm owns the form state and the validation schema, defineField returns a v-model-ready ref plus attributes for each input, and handleSubmit runs validation before your submit code.
  • Describing the rules as a schema (Zod, Yup, Valibot) keeps them in one place, and with toTypedSchema the form values are typed from that same schema.
  • FormKit takes the opposite approach to VeeValidate: inputs, labels, error messages, and validation rules are all props on one FormKit component, which trades markup control for speed.

A form is a small state machine

A sign-up form looks like three inputs and a button. Count the state behind it and you get something closer to a small state machine:

  • each field’s value
  • each field’s error message, if any
  • whether each field has been touched (you don’t want to shout “required” at someone who hasn’t reached the field yet)
  • whether the form as a whole is valid
  • whether it is submitting, so the button can be disabled and a double click doesn’t send two requests
  • server errors (“that email is already registered”) that must appear next to the right field

v-model handles the first item. Everything else is yours to build. The browser’s own constraint validation (required, type="email", pattern) covers simple cases and is explained in forms and form validation; this lesson is about doing it in Vue when you need custom messages, cross-field rules, and full control over when errors appear.

One rule before any code: client-side validation exists for the user’s benefit. The server has to check every rule again, because nothing running in the browser can be trusted.

Doing it by hand

For a small form, refs and computed values are enough, and writing one by hand shows what a library will automate:

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'

const form = reactive({ email: '', password: '' })
const touched = reactive({ email: false, password: false })
const submitting = ref(false)

const errors = computed(() => ({
  email: !form.email ? 'Email is required'
    : !/^\S+@\S+\.\S+$/.test(form.email) ? 'Enter a valid email' : '',
  password: form.password.length < 8 ? 'At least 8 characters' : '',
}))
const isValid = computed(() => !errors.value.email && !errors.value.password)

async function onSubmit() {
  touched.email = touched.password = true
  if (!isValid.value) return
  submitting.value = true
  try { await api.signUp(form) } finally { submitting.value = false }
}
</script>

<template>
  <form @submit.prevent="onSubmit" novalidate>
    <input v-model="form.email" @blur="touched.email = true" type="email" />
    <p v-if="touched.email && errors.email">{{ errors.email }}</p>
    <!-- password field: the same pattern again -->
    <button :disabled="submitting">Sign up</button>
  </form>
</template>

This is fine for two fields. With ten fields, async checks (“is this username taken?”), and rules that compare fields (“passwords must match”), you are writing the same touched/error/valid bookkeeping again and again. Because it’s the same every time, it’s a natural fit for a composable, and that is what VeeValidate is.

VeeValidate: the bookkeeping as composables

VeeValidate (version 4 is current for Vue 3) gives you that state machine as composables. You describe the rules once, as a schema, and it tracks values, errors, touched and dirty flags, and submission for you. Here is the same form with a Zod schema:

<script setup lang="ts">
import { useForm } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
import { z } from 'zod'

const schema = toTypedSchema(
  z.object({
    email: z.string().min(1, 'Email is required').email('Enter a valid email'),
    password: z.string().min(8, 'At least 8 characters'),
  }),
)

const { defineField, errors, handleSubmit, isSubmitting } = useForm({
  validationSchema: schema,
})

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

const onSubmit = handleSubmit(async (values, { setErrors }) => {
  try {
    await api.signUp(values) // values is typed { email: string; password: string }
  } catch (e) {
    setErrors({ email: 'That email is already registered' })
  }
})
</script>

<template>
  <form @submit="onSubmit" novalidate>
    <input v-model="email" v-bind="emailAttrs" type="email" />
    <p v-if="errors.email">{{ errors.email }}</p>

    <input v-model="password" v-bind="passwordAttrs" type="password" />
    <p v-if="errors.password">{{ errors.password }}</p>

    <button :disabled="isSubmitting">Sign up</button>
  </form>
</template>

Each piece does one job:

  • useForm owns the form state and the schema. It also provides that state to descendant components, so a field component deep in the tree can join the same form.
  • defineField('email') returns a pair: a ref you bind with v-model, and a ref of attributes (blur and input listeners) you spread with v-bind, so VeeValidate knows when the user has interacted with the field.
  • handleSubmit(fn) returns a submit handler that prevents the default, validates everything, and only calls fn with clean values if the form is valid. The second argument gives you actions like setErrors and resetForm, which is how server errors land next to the right field.
  • toTypedSchema connects the schema to TypeScript, so values is typed from the same Zod object that validates it.

A version note: the @vee-validate/zod adapter for VeeValidate 4.15 declares Zod 3 as its peer dependency. If your project is on Zod 4, the zod package still ships the Zod 3 API under zod/v3, and a VeeValidate 5 is in beta at the time of writing; check the VeeValidate docs for the pairing that matches your versions.

VeeValidate also ships <Form>, <Field>, and <ErrorMessage> components that wrap the same machinery for people who prefer templates. Older tutorials, including the video, use useField per input; defineField is the newer, shorter helper for the common case of binding a native input.

For a reusable input component, useField('email') inside the component is still the right tool: the component gets its own value, error, and meta, and connects to the nearest parent useForm through injection. That is the same v-model on components pattern you already know, with validation attached.

FormKit: the component-first alternative

FormKit makes the opposite trade. Instead of composables you wire to your own markup, it gives you one <FormKit> component that renders the label, the input, help text, and error messages, with validation rules as a string:

<FormKit type="form" @submit="signUp">
  <FormKit type="email" name="email" label="Email" validation="required|email" />
  <FormKit type="password" name="password" label="Password" validation="required|length:8" />
</FormKit>

That is far less code, and FormKit handles accessibility details like linking labels and errors. The cost is control over the generated markup, which you change through FormKit’s theming and schema system instead of plain HTML. If your design system already has input components, VeeValidate fits around them; if you want working forms fast and can accept FormKit’s markup, it’s quicker.

React developers will recognise the split: VeeValidate sits roughly where React Hook Form does, a headless state layer you attach to your own inputs.

What the video covers

Mohit Kumar Toshniwal builds one email-and-password form twice with VeeValidate and Zod: first with the <Form>, <Field>, and <ErrorMessage> components, then with useForm and useField, both using toTypedSchema. It’s a clear, correct, compact demo of the library’s two styles. It doesn’t cover the hand-rolled baseline, defineField, server errors, or FormKit; the sections above add those. The first runner-up is a talk by VeeValidate’s author on composing forms out of components.

Where this fits

Forms build on v-model on components and composables. Next: testing components with Vitest and Vue Test Utils.

Check yourself

  1. 01Why does VeeValidate's `handleSubmit` return a new function instead of handling the submit event itself?

    `handleSubmit(fn)` wraps your callback in a handler that validates every field first, marks them touched so errors show, and only calls `fn` with the validated values when the form is valid. Returning a function lets you attach it wherever you like, typically `@submit="onSubmit"` on the form, and it also prevents the browser's default submit for you.

  2. 02A form validates that the email field is a well-formed address. Why do you still need server-side validation of the same field?

    Client-side code runs on the user's machine and can be bypassed entirely, by disabling JavaScript, editing the page, or sending a request straight to the API. Client validation only exists to give fast feedback; the server is the only place a rule can actually be enforced.

  3. 03What do you get back from `const [email, emailAttrs] = defineField('email')`, and how do you use the two values?

    `email` is a ref holding the field's value, which you bind with `v-model="email"`. `emailAttrs` is a ref of extra attributes such as blur and input listeners, which you spread with `v-bind="emailAttrs"` so VeeValidate knows when the field was touched and when to validate.

  4. 04When might you pick a hand-rolled form with refs and computed values over a validation library?

    For a small form with one or two fields and simple rules, such as a search box or a newsletter signup. A computed error message per field is a few lines and adds no dependency; the library starts paying off once you have many fields, cross-field rules, async checks, or server errors to merge in.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark