Guides

Forms and validation

Build forms with Vuetify, reusable rules, a submit helper, server errors and schema-driven forms.

composables/useFormSubmit.ts
View in the demo

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.tsReusable rules with translated messages.
useFormSubmit()composables/useFormSubmit.tsValidates, focuses the first error, handles loading, double submits and server errors.
Base* inputscomponents/ui/inputs/Vuetify inputs with the template style, a visible label and “(optional)”.

A form from scratch

vue
<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 by useFormSubmit.
  • @submit.prevent="submit" plus a type="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.

ts
: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:

composables/useFormRules.ts
function postalCode(message?: string): ValidationRule {
  return optional((value) => /^\d{5}$/.test(toText(value)), message || t('form.rules.postalCode'))
}

What useFormSubmit returns

Value
Use
formRefThe 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.
isSubmittingBind it to :loading on the primary button.
isSuccessShow a message or a success state.
formErrorThe general error, ready to display.
fieldErrorsServer errors per field for :error-messages. Each one clears when the user edits that field.
errorCountInvalid 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:

vue
<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.

ts
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 registeringError on the email field.
Password wrong-passwordWrong credentials or wrong current password.
Username admin in account settingsUsername already taken.
Code PRD-001 when creating a productDuplicate 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.

ts
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'] },
    ],
  },
]
  • rules accepts names ('required', 'email'…), tuples (['minLength', 8], ['match', 'password']) or any rule from useFormRules().
  • Fields without 'required' are marked optional automatically.
  • Set server errors with a ref and setErrors(resolveSubmitError(error).fieldErrors).
  • Put secondary or destructive actions in the #actions-start slot, left of Cancel and Save. Delete uses BaseButton button-type="danger" and confirms with useConfirm().

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 hint and persistent-hint.
  • Error messages say how to fix the problem.
  • Set type, inputmode and autocomplete (email, tel, cc-number, new-password…).
  • Groups (BaseRadioGroup, BaseCheckboxGroup, BaseToggleGroup) render a fieldset with a legend and accept rules like any field.
  • info adds a help icon with a tooltip next to the label for context that does not fit in the hint.
© 2026 melsami UI.
Developer documentation for melsami UI.