My account

Forms and validation in Vue

v-model connects an input to state, and defineModel makes your own input components work with v-model. Keep the rules in one schema, show an error only after the user has touched a field or tried to submit, link each error to its input for screen readers, block double submits, and always validate again on the server.

Not reviewedWritten with AI helpReading time: 15 minOnline shop exampleVue 3.5 code

Author: bezzad

Contents

The problem: a checkout form that annoys people

Our shop has a checkout form with name, email, phone and address. Support got these reports:

  1. The form is red before I type anything. Every field shows “required” when the page opens.
  2. I clicked “Pay” twice and got two orders.
  3. A screen reader user cannot tell which field is wrong. The error is only red text.
  4. A test with curl created an order with an empty address. The rules exist only in the browser.

Let us build the form step by step and fix each one.

v-model: an input and a value stay in sync

<script setup lang="ts">
import { reactive } from 'vue';

const form = reactive({ name: '', email: '', quantity: 1 });
</script>

<template>
  <label for="name">Name</label>
  <input id="name" v-model.trim="form.name" autocomplete="name" />

  <label for="qty">Quantity</label>
  <input id="qty" v-model.number="form.quantity" type="number" min="1" />
</template>
  1. v-model is short for “bind the value and update it on input”.
  2. .trim removes spaces at the start and end. .number turns the text into a number. .lazy updates on change (when the user leaves the field) instead of on every key.
  3. Every input needs a real label with for, not only a placeholder. A placeholder disappears when the user types.
  4. autocomplete lets the browser fill the name, email and address. On a phone this saves a lot of typing.

defineModel: your own input with v-model

Most apps wrap inputs in a component with a label and an error. defineModel (Vue 3.4 and newer) makes v-model work on it.

<!-- TextField.vue -->
<script setup lang="ts">
const model = defineModel<string>({ required: true });
defineProps<{ id: string; label: string; error?: string }>();
</script>

<template>
  <label :for="id">{{ label }}</label>
  <input
    :id="id"
    v-model="model"
    :aria-invalid="!!error"
    :aria-describedby="error ? `${id}-error` : undefined"
  />
  <p v-if="error" :id="`${id}-error`" class="error">{{ error }}</p>
</template>
<TextField id="email" label="Email" v-model="form.email" :error="errors.email" />
  1. defineModel gives a ref. Reading it reads the parent value. Writing it sends the update:modelValue event to the parent. The child never changes a prop directly.
  2. aria-invalid and aria-describedby tell a screen reader that the field is wrong and read the error text. This fixes report 3.

One schema for the rules

Write the rules once, in a schema. Zod is a common choice. VeeValidate can use the same schema and track touched fields for you.

import { z } from 'zod';

export const checkoutSchema = z.object({
  name: z.string().min(2, 'Write your full name'),
  email: z.string().email('This email looks wrong'),
  phone: z.string().regex(/^\+?[0-9 ]{7,15}$/, 'Use only numbers'),
  address: z.string().min(10, 'Write the full address'),
});

export type Checkout = z.infer<typeof checkoutSchema>;
  1. The same schema can run in the browser and on the server (for example in a Node or Nuxt API). The rules never get out of sync.
  2. Error text says how to fix it, not only “invalid”.
  3. Do not make rules stricter than real life. Names can have one letter, spaces or an apostrophe. Phone numbers have many formats.

When to show an error

Page opensLeaves emailPresses PayFixes emailErrors at once4 errors4 errors4 errors3 errorsAfter blur or submitcleanemail onlyall errorsemail is fineTime
Showing every error on page load punishes users before they start. Show a field's error after the user leaves it (blur), and show all errors when they press submit. After that, update the error on every key, so it goes away as soon as the value is fixed.
const touched = reactive<Record<string, boolean>>({});
const submitted = ref(false);

const result = computed(() => checkoutSchema.safeParse(form));

const errors = computed(() => {
  if (result.value.success) return {};
  const all = result.value.error.flatten().fieldErrors;
  const shown: Record<string, string> = {};
  for (const [field, messages] of Object.entries(all)) {
    if (submitted.value || touched[field]) shown[field] = messages![0];
  }
  return shown;
});
  1. The errors are a computed from the form. There is no watch that copies values around.
  2. Mark a field as touched on blur: @blur="touched.email = true".
  3. On submit with errors, move the focus to the first wrong field, so keyboard and screen reader users find it.

Submit once, and trust only the server

Browser checkschemaDisable button, sendIdempotency-KeyServer checks againsame schemaField errorsshown next to each fieldOne order savedthank you pageA second request with the same key gets the same answer, not a new order
On submit: validate in the browser, then disable the button and send. The server validates again. If it returns field errors, show them next to the fields. The idempotency key makes a second request for the same order safe.
const submitting = ref(false);
const orderKey = crypto.randomUUID(); // one key for this checkout

async function onSubmit() {
  submitted.value = true;
  if (!result.value.success || submitting.value) return;

  submitting.value = true;
  try {
    await api.createOrder(result.value.data, { idempotencyKey: orderKey });
    router.push('/thank-you');
  } catch (e) {
    if (e instanceof ValidationError) serverErrors.value = e.fields;
    else formError.value = 'We could not save your order. Try again.';
  } finally {
    submitting.value = false;
  }
}
<form @submit.prevent="onSubmit" novalidate>
  <!-- fields -->
  <button type="submit" :disabled="submitting">Pay</button>
</form>
  1. @submit.prevent handles the Enter key too and stops the page reload. Do not use only a click handler on the button.
  2. The submitting flag blocks a second click. But a flag is not enough: a slow network, a retry or two tabs can still send twice. The idempotency key lets the server see that it is the same order. This fixes report 2.
  3. The server validates again, with the same schema. The browser check is only for a nice user experience. Anyone can send a request without your form. This fixes report 4.
  4. Show server field errors (like “this email is already used”) next to the field, not only as a toast.
  5. novalidate turns off the browser’s own popups, so you show your own, consistent messages. Keep the right input types (type="email", inputmode="numeric") for the phone keyboard.

Common mistakes

Mistake Result Better way
All errors shown on page load The form feels like it shouts. Show after blur or after submit.
Placeholder instead of label The hint disappears; screen readers miss it. A real label with for.
Error only as red color Color-blind and screen reader users miss it. Text, aria-invalid, aria-describedby.
A child changes its prop Vue warns; two owners for one value. defineModel or emit an update event.
Rules only in the browser Bad data from other clients. Same schema on the server.
Only a disabled button against double submit Two orders on retry or slow network. Plus an idempotency key on the server.

Summary in 6 lines

  1. v-model keeps an input and a value in sync. Use .trim and .number where they help.
  2. defineModel makes your own input components work with v-model, without changing a prop.
  3. Keep the rules in one schema and use it in the browser and on the server.
  4. Show an error after blur or submit, with text that says how to fix it.
  5. Link errors to inputs with aria-invalid and aria-describedby, and focus the first wrong field.
  6. Block double submits in the UI and with an idempotency key on the server.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.