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.
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:
- The form is red before I type anything. Every field shows “required” when the page opens.
- I clicked “Pay” twice and got two orders.
- A screen reader user cannot tell which field is wrong. The error is only red text.
- 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>
- v-model is short for “bind the value and update it on input”.
- .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.
- Every input needs a real label with
for, not only a placeholder. A placeholder disappears when the user types. - 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" />
- defineModel gives a ref. Reading it reads the parent value. Writing it sends the
update:modelValueevent to the parent. The child never changes a prop directly. - 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>;
- 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.
- Error text says how to fix it, not only “invalid”.
- 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
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;
});
- The errors are a computed from the form. There is no watch that copies values around.
- Mark a field as touched on blur:
@blur="touched.email = true". - 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
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>
- @submit.prevent handles the Enter key too and stops the page reload. Do not use only a click handler on the button.
- The
submittingflag 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. - 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.
- Show server field errors (like “this email is already used”) next to the field, not only as a toast.
- 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
- v-model keeps an input and a value in sync. Use .trim and .number where they help.
- defineModel makes your own input components work with v-model, without changing a prop.
- Keep the rules in one schema and use it in the browser and on the server.
- Show an error after blur or submit, with text that says how to fix it.
- Link errors to inputs with aria-invalid and aria-describedby, and focus the first wrong field.
- Block double submits in the UI and with an idempotency key on the server.