Guides
Forms and validation
Build forms with Vuetify, reusable rules, a submit helper, server errors and schema-driven forms.
Forms are plain Vuetify: v-form, :rules, hint and error-messages. On top of that the template adds three small pieces:
Piece | File | Purpose |
|---|---|---|
useFormRules() | composables/useFormRules.ts | Reusable rules with translated messages. |
useFormSubmit() | composables/useFormSubmit.ts | Validates, focuses the first error, handles loading, double submits and server errors. |
Base* inputs | components/ui/inputs/ | Vuetify inputs with the template style, a visible label and “(optional)”. |
A form from scratch
<template>
<v-form ref="formRef" class="d-flex flex-column ga-4" @submit.prevent="submit">
<BaseFormFeedback :error="formError" :success="isSuccess ? $t('newsletter.done') : undefined" />
<BaseTextField
v-model="values.email"
:label="$t('newsletter.email')"
:placeholder="$t('newsletter.emailPlaceholder')"
:rules="[rules.required(), rules.email()]"
:error-messages="fieldErrors.email"
type="email"
inputmode="email"
autocomplete="email"
hide-details="auto"
/>
<BaseTextField
v-model="values.company"
:label="$t('newsletter.company')"
autocomplete="organization"
optional
hide-details="auto"
/>
<BaseButton button-type="primary" type="submit" :loading="isSubmitting">
{{ $t('newsletter.submit') }}
</BaseButton>
</v-form>
</template>
<script setup lang="ts">
interface NewsletterPayload {
email: string
company: string
}
const rules = useFormRules()
const values = reactive<NewsletterPayload>({ email: '', company: '' })
const { formRef, isSubmitting, isSuccess, formError, fieldErrors, submit } = useFormSubmit(
values,
(payload) => $fetch('/api/newsletter', { method: 'POST', body: payload })
)
</script>
Three details matter:
ref="formRef"must match the name returned byuseFormSubmit.@submit.prevent="submit"plus atype="submit"button makes Enter submit too.hide-details="auto"reserves space for a message only when there is one.
Mark optional fields with optional. Never mark required ones.
Validation rules
Every rule returns a standard Vuetify function (value) => true | string, so you can mix them with your own.
Rule | Validates |
|---|---|
required() | Not empty: trimmed text, an array with items; false counts as empty. |
accepted() | A checked checkbox (true). |
email(), url(), phone() | Format. phone accepts +, spaces, dashes and brackets, 7 to 15 digits. |
numeric(), integer(), positive() | Numbers. |
min(n), max(n) | Numeric value. |
minLength(n), maxLength(n) | Text length. |
pattern(regex, message?) | A regular expression. Always pass a message that explains the format. |
password(min = 8) | Minimum length, at least one letter and one number. |
sameAs(() => other) | Equal to another field, such as a password confirmation. |
All rules except required and accepted accept an empty value. If the field is mandatory, put required() first.
:rules="[rules.required(), rules.minLength(3)]"
:rules="[rules.sameAs(() => values.password)]"
Custom messages and new rules
Every rule takes its message as the last argument: rules.required(t('checkout.errors.cardRequired')). To change a default message for the whole app, edit form.rules.* in locales/<code>/common.json.
To reuse a new rule, add it to useFormRules.ts with its form.rules.<name> key in every common.json:
function postalCode(message?: string): ValidationRule {
return optional((value) => /^\d{5}$/.test(toText(value)), message || t('form.rules.postalCode'))
}
What useFormSubmit returns
Value | Use |
|---|---|
formRef | The ref of the v-form. |
submit() | Validates, focuses the first invalid field and calls your handler when valid. Ignores clicks while a submit is running. |
isSubmitting | Bind it to :loading on the primary button. |
isSuccess | Show a message or a success state. |
formError | The general error, ready to display. |
fieldErrors | Server errors per field for :error-messages. Each one clears when the user edits that field. |
errorCount | Invalid fields after the first attempt. |
focusNextError() | Moves to the next invalid field, for the error summary button. |
resetValidation() | Clears errors after emptying the form. |
For long forms, show a summary at the top so the user knows why they cannot continue:
<BaseFormFeedback :error="formError" :error-count="errorCount" @review="focusNextError" />
If the submit fails, the values stay as they are, so the user only fixes and submits again.
Server errors
Throw a FormSubmitError from your handler. fieldErrors uses the keys of values; messages may be plain text or i18n keys.
throw new FormSubmitError({
message: 'Check the highlighted fields',
fieldErrors: { email: ['This email is already registered'] },
})
If your API answers 422 with { message, errors }, toFormSubmitError(error) does the conversion for you. Any other error shows the generic form.errors.server message.
The demo mocks react to these values so you can see every state without a backend:
Value | Result |
|---|---|
[email protected] | General server error. |
[email protected] when registering | Error on the email field. |
Password wrong-password | Wrong credentials or wrong current password. |
Username admin in account settings | Username already taken. |
Code PRD-001 when creating a product | Duplicate code. |
When validation runs
Fields validate when you leave them and, once a field has an error, again on every keystroke so the error disappears as soon as it is fixed. That is Vuetify's validate-on="invalid-input", set for every form in vuetify.config.ts. Change it globally there, for one form with <v-form validate-on="submit">, or for one field with validate-on="input".
Schema-driven forms with BaseForm
For CRUD screens with many fields, BaseForm builds the form from an array of sections. It supports the panel, page, aside, tabs and stepper layouts, drafts, an unsaved changes warning and the error summary.
const sections: FormSection[] = [
{
key: 'info',
title: t('products.sections.info'),
fields: [
{ key: 'name', type: 'text', label: t('products.name'), rules: ['required', ['maxLength', 80]] },
{ key: 'email', type: 'email', label: t('products.contact'), rules: ['email'] },
],
},
]
rulesaccepts names ('required','email'…), tuples (['minLength', 8],['match', 'password']) or any rule fromuseFormRules().- Fields without
'required'are marked optional automatically. - Set server errors with a
refandsetErrors(resolveSubmitError(error).fieldErrors). - Put secondary or destructive actions in the
#actions-startslot, left of Cancel and Save. Delete usesBaseButton button-type="danger"and confirms withuseConfirm().
Create and edit dialogs combine BaseFormPanel with BaseForm. Every layout can be tried in the demo under Forms, Overview.
Accessibility checklist
- The label is always visible. Use the placeholder only for an example of the format.
- Explain rules before the error with
hintandpersistent-hint. - Error messages say how to fix the problem.
- Set
type,inputmodeandautocomplete(email,tel,cc-number,new-password…). - Groups (
BaseRadioGroup,BaseCheckboxGroup,BaseToggleGroup) render afieldsetwith alegendand acceptruleslike any field. infoadds a help icon with a tooltip next to the label for context that does not fit in the hint.