Skip to content

Search documentation

Search guides, examples, and component APIs.

Quick links
↑↓ NavigateEnter OpenEsc Close
Get started

Documentation navigation

Components / Forms

Form

Connects named controls to Vee Validate or Kern form state.

Last changed in version 0.14.2: Improve keyboard navigation, action feedback, and selected colors across Vue components.

Interactive showcase

Install

Run in your project
bunx --bun @getweini/cli@latest add form input button alert stepper

Start with this example

Import the files copied by the install command, then place the component in your Vue template. The text and values in the example belong to your app; change them to fit your task.

Vue
<script setup lang="ts">
import { useForm } from 'vee-validate'
import { computed, ref, useId, watch } from 'vue'
import Alert from './components/ui/alert/Alert.vue'
import AlertTitle from './components/ui/alert/AlertTitle.vue'
import Button from './components/ui/button/Button.vue'
import Form from './components/ui/form/Form.vue'
import Input from './components/ui/input/Input.vue'
import Stepper from './components/ui/stepper/Stepper.vue'

const emailId = useId()
const nameId = useId()
const { values, setFieldError } = useForm({
  initialValues: { email: '', displayName: '' },
  validationSchema: {
    displayName: (value: string) => Boolean(value.trim()) || 'Enter your display name.',
    email: (value: string) =>
      /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) || 'Enter a valid email address.',
  },
})
const step = ref('details')
const steps = computed(() => [
  { value: 'details', label: 'Details' },
  { value: 'saved', label: 'Saved', disabled: step.value !== 'saved' },
])
const errors = ref<Record<string, string[]>>({})
const pending = ref(false)
const saveError = ref(false)
const serverFieldError = ref(false)
let failedOnce = false

watch(
  () => [values.email, values.displayName],
  ([email], [previousEmail]) => {
    errors.value = {}
    if (serverFieldError.value && email !== previousEmail) {
      serverFieldError.value = false
      setFieldError('email', undefined)
    }
  },
)

async function save(submitted: unknown) {
  if (pending.value) return
  errors.value = {}
  saveError.value = false
  pending.value = true
  const { email, displayName } = submitted as { email: string; displayName: string }
  try {
    await new Promise((resolve) => setTimeout(resolve, 500))
    if (values.email !== email || values.displayName !== displayName) return
    if (email.toLowerCase() === 'taken@example.com') {
      serverFieldError.value = true
      const message = 'This email is already registered. Try a different address.'
      setFieldError('email', message)
      errors.value = { email: [message] }
    } else if (!failedOnce) {
      failedOnce = true
      saveError.value = true
    } else {
      step.value = 'saved'
    }
  } finally {
    pending.value = false
  }
}
</script>

<template>
  <div class="space-y-4">
    <Stepper :model-value="step" :items="steps" label="Save progress" linear />
    <Alert v-if="step === 'saved'" variant="success" role="status">
      <AlertTitle>Email saved</AlertTitle>
    </Alert>
    <Form
      v-else
      focus-on-invalid-submit
      :announce-field-errors="false"
      class="space-y-3"
      @submit="save"
      @reset="errors = {}; saveError = false"
      @invalid-submit="({ errors: messages }) => (errors = messages)"
    >
      <Alert v-if="Object.keys(errors).length" variant="destructive" role="alert">
        <AlertTitle>Check your details</AlertTitle>
        <ul class="space-y-1">
          <li v-if="errors.displayName?.length">
            <a :href="`#${nameId}`" class="underline">{{ errors.displayName[0] }}</a>
          </li>
          <li v-if="errors.email?.length">
            <a :href="`#${emailId}`" class="underline">{{ errors.email[0] }}</a>
          </li>
        </ul>
      </Alert>
      <Alert v-if="saveError" variant="destructive" role="alert">
        <AlertTitle>Could not save your email</AlertTitle>
        <p>Your draft is still here. Try saving again.</p>
      </Alert>
      <label :for="nameId">Display name</label>
      <Input :id="nameId" name="displayName" autocomplete="name" :readonly="pending" />
      <label :for="emailId">Email</label>
      <Input :id="emailId" name="email" type="email" autocomplete="email" :readonly="pending" />
      <div class="flex gap-2">
        <Button type="submit" :loading="pending">{{ saveError ? 'Try again' : 'Save' }}</Button>
        <Button type="reset" variant="outline" :disabled="pending">Reset</Button>
      </div>
      <span v-if="pending" role="status" class="sr-only">Saving email</span>
    </Form>
  </div>
</template>

Call useForm with initialValues and a Vee rule object or validation schema in the parent. Then use Form and named controls in the template.

When to use it

Vee Validate rules

Use a validator function in the useForm validationSchema object.

Kern form state

Use useKernForm with a Kern schema and named controls.

More examples

Save and recover from errors

Submit an empty email to see field focus and the error summary. Try taken@example.com to see a server field error. A different valid email shows a retryable failure on the first save.

Save and recover from errors
<script setup lang="ts">
import { useForm } from 'vee-validate'
import { computed, ref, useId, watch } from 'vue'
import Alert from './components/ui/alert/Alert.vue'
import AlertTitle from './components/ui/alert/AlertTitle.vue'
import Button from './components/ui/button/Button.vue'
import Form from './components/ui/form/Form.vue'
import Input from './components/ui/input/Input.vue'
import Stepper from './components/ui/stepper/Stepper.vue'

const emailId = useId()
const nameId = useId()
const { values, setFieldError } = useForm({
  initialValues: { email: '', displayName: '' },
  validationSchema: {
    displayName: (value: string) => Boolean(value.trim()) || 'Enter your display name.',
    email: (value: string) =>
      /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) || 'Enter a valid email address.',
  },
})
const step = ref('details')
const steps = computed(() => [
  { value: 'details', label: 'Details' },
  { value: 'saved', label: 'Saved', disabled: step.value !== 'saved' },
])
const errors = ref<Record<string, string[]>>({})
const pending = ref(false)
const saveError = ref(false)
const serverFieldError = ref(false)
let failedOnce = false

watch(
  () => [values.email, values.displayName],
  ([email], [previousEmail]) => {
    errors.value = {}
    if (serverFieldError.value && email !== previousEmail) {
      serverFieldError.value = false
      setFieldError('email', undefined)
    }
  },
)

async function save(submitted: unknown) {
  if (pending.value) return
  errors.value = {}
  saveError.value = false
  pending.value = true
  const { email, displayName } = submitted as { email: string; displayName: string }
  try {
    await new Promise((resolve) => setTimeout(resolve, 500))
    if (values.email !== email || values.displayName !== displayName) return
    if (email.toLowerCase() === 'taken@example.com') {
      serverFieldError.value = true
      const message = 'This email is already registered. Try a different address.'
      setFieldError('email', message)
      errors.value = { email: [message] }
    } else if (!failedOnce) {
      failedOnce = true
      saveError.value = true
    } else {
      step.value = 'saved'
    }
  } finally {
    pending.value = false
  }
}
</script>

<template>
  <div class="space-y-4">
    <Stepper :model-value="step" :items="steps" label="Save progress" linear />
    <Alert v-if="step === 'saved'" variant="success" role="status">
      <AlertTitle>Email saved</AlertTitle>
    </Alert>
    <Form
      v-else
      focus-on-invalid-submit
      :announce-field-errors="false"
      class="space-y-3"
      @submit="save"
      @reset="errors = {}; saveError = false"
      @invalid-submit="({ errors: messages }) => (errors = messages)"
    >
      <Alert v-if="Object.keys(errors).length" variant="destructive" role="alert">
        <AlertTitle>Check your details</AlertTitle>
        <ul class="space-y-1">
          <li v-if="errors.displayName?.length">
            <a :href="`#${nameId}`" class="underline">{{ errors.displayName[0] }}</a>
          </li>
          <li v-if="errors.email?.length">
            <a :href="`#${emailId}`" class="underline">{{ errors.email[0] }}</a>
          </li>
        </ul>
      </Alert>
      <Alert v-if="saveError" variant="destructive" role="alert">
        <AlertTitle>Could not save your email</AlertTitle>
        <p>Your draft is still here. Try saving again.</p>
      </Alert>
      <label :for="nameId">Display name</label>
      <Input :id="nameId" name="displayName" autocomplete="name" :readonly="pending" />
      <label :for="emailId">Email</label>
      <Input :id="emailId" name="email" type="email" autocomplete="email" :readonly="pending" />
      <div class="flex gap-2">
        <Button type="submit" :loading="pending">{{ saveError ? 'Try again' : 'Save' }}</Button>
        <Button type="reset" variant="outline" :disabled="pending">Reset</Button>
      </div>
      <span v-if="pending" role="status" class="sr-only">Saving email</span>
    </Form>
  </div>
</template>

Zod schema

Use the same named Input with a Standard Schema.

Zod schema
<script setup lang="ts">
import { useForm } from 'vee-validate'
import * as z from 'zod'
import Button from './components/ui/button/Button.vue'
import Form from './components/ui/form/Form.vue'
import Input from './components/ui/input/Input.vue'

useForm({
  initialValues: { email: '' },
  validationSchema: z.object({ email: z.email() }),
})

function save(values: unknown) {
  console.log(values)
}
</script>

<template>
  <Form @submit="save">
    <label for="vee-email">Email</label>
    <Input id="vee-email" name="email" type="email" />
    <Button type="submit">Save</Button>
  </Form>
</template>

Kern form

Use Kern for both form values and validation.

Kern form
<script setup lang="ts">
import { useKernForm } from '@getweini/vue/primitives/form-kern'
import { object, string } from '@sousaivan/kern/validation'
import { ref, useId } from 'vue'
import Alert from './components/ui/alert/Alert.vue'
import AlertTitle from './components/ui/alert/AlertTitle.vue'
import Button from './components/ui/button/Button.vue'
import Form from './components/ui/form/Form.vue'
import Input from './components/ui/input/Input.vue'

const emailId = useId()
const errors = ref<Record<string, string[]>>({})
const saved = ref(false)

useKernForm({
  initialValues: { email: '' },
  schema: object({ email: string().email() }),
})

function resetFeedback() {
  errors.value = {}
  saved.value = false
}
</script>

<template>
  <Form
    focus-on-invalid-submit
    class="space-y-3"
    @submit="resetFeedback(); saved = true"
    @invalid-submit="({ errors: messages }) => { errors = messages; saved = false }"
    @reset="resetFeedback"
  >
    <Alert v-if="errors.email?.length" variant="destructive">
      <AlertTitle>Check your details</AlertTitle>
      <a :href="`#${emailId}`" class="underline">Review your email address</a>
    </Alert>
    <label :for="emailId">Email</label>
    <Input :id="emailId" name="email" type="email" autocomplete="email" @input="resetFeedback" />
    <div class="flex gap-2">
      <Button type="submit">Save</Button>
      <Button type="reset" variant="outline">Reset</Button>
    </div>
    <Alert v-if="saved" variant="success" role="status">
      <AlertTitle>Email saved</AlertTitle>
    </Alert>
  </Form>
</template>

Complete API

Every public prop, model, event, slot, and exposed member of the installed Vue parts is listed below. “Not set” means you can leave that value out; “Required” means you must provide it. Native HTML attributes also work where the component uses a native element.

Form

Complete API for Form
NameType or signatureDefaultWhat it does
novalidatepropboolean | undefinedtrueControls the novalidate behavior of Form.
focusOnInvalidSubmitpropboolean | undefinedfalseControls the focus on invalid submit behavior of Form.
announceFieldErrorspropboolean | undefinedtrueControls the announce field errors behavior of Form.
submitevent[values: unknown]—Emitted when submit happens.
invalid-submitevent[payload: { errors: Record<string, string[]>; }]—Emitted when invalid submit happens.
defaultslot{}OptionalContent shown inside Form.
Public type definitions
Public types
// packages/frameworks/vue/components/form/types.ts
export interface FormProps {
  novalidate?: boolean
  focusOnInvalidSubmit?: boolean
  announceFieldErrors?: boolean
}

Implementation notes

  • Use weini init --form vee --form-schema custom for Vee rules, or choose a provider interactively. Run weini setup form to change it later.
  • The published Vee Validate 5 Standard Schema support is currently in 5.0.0-beta.1.
  • For Kern-owned form state, choose --form kern and call useKernForm({ initialValues, schema }) from @getweini/vue/primitives/form-kern.
  • The CLI installs the selected provider implementation as Form.vue; use the same import for either provider.
  • Controls with name read initial values, update form state, and show errors after blur or submit. The error slot receives message and messages.

Accessibility and localization

  • Keep a visible label for each control. Automatic errors are connected with aria-describedby and invalid controls receive aria-invalid.
  • Use focusOnInvalidSubmit to focus the first invalid field. If you announce a linked error summary yourself, set announceFieldErrors to false so the inline errors stay available as field descriptions.

Source contract and editing guidance