Skip to content
LIBRARYFormsUpdated

Form Errors ​

An actionable error summary that reveals the owning section before focusing its editor.

Available in alpha.5

Available in Mavis alpha.5.

Web preview
Open example ↗

Create one useFormController() per form. Register fields with useFormField(form, { name, label, target, enabled?, reveal? }), where target returns an InputHandle. The controller never queries a DOM ID or owns the draft. reveal can activate a cached step and await Vue nextTick() before resolving the mounted handle.

PropTypeDefaultPurpose
formFormControllerrequiredRequest/component-owned controller.
titlestringReview these fieldsVisible summary heading.
announcebooleanfalseOpt-in Web alert role; otherwise a named region.

form.setErrors([{ field, message }]) replaces the summary without focusing automatically. await form.focusFirstError() is an explicit host action, normally after an unsuccessful submission. Unregistered or disabled fields are skipped; their messages remain visible. Clicking an available error invokes focusError(field) and emits focus(field, focused). Only one outstanding focus operation owns the result, preventing a late section reveal from stealing a later focus request.

await form.validate(async ({ current, onCancel }) => errors) returns valid, invalid, cancelled or busy. Concurrent submissions return busy. Call form.invalidate() when the host draft changes; obsolete success and failure cannot overwrite newer errors. Register transport cancellation through onCancel. Current transport errors are rethrown for the host to present; they are not field errors. No network transport, schema library or validation rule is built in.

Vue composables release field registrations and dispose controllers on scope disposal. Cached fields only expose their handle while active; supply reveal when errors can point into another step. Register all step fields in the owning form if a summary must reach an unvisited step. Keep draft values and the retained panel lifecycle in the host. SSR renders only the provided errors; it does not focus or validate automatically.

vue
<script setup lang="ts">
import { useCatalogLocale } from '../locale'
import { computed, onScopeDispose, ref, shallowRef } from 'vue'
import type { InputHandle } from '@getcortexlabs/mavis-core'
import { useFormController, useFormField } from '@getcortexlabs/mavis-core/vue'

const { t, locale } = useCatalogLocale(() => props.lang)

const props = withDefaults(defineProps<{ lang?: 'en' | 'pt' }>(), { lang: undefined })

const pt = computed(() => (props.lang ?? locale.value) === 'pt')
const name = ref('')
const email = ref('')
const nameInput = ref<InputHandle>()
const emailInput = ref<InputHandle>()
const form = useFormController()
const state = shallowRef(form.state)
const saved = ref(false)
onScopeDispose(
  form.subscribe((next) => {
    state.value = next
  }),
)
useFormField(form, {
  name: 'name',
  label: pt.value ? 'Nome' : 'Name',
  target: () => nameInput.value,
})
useFormField(form, { name: 'email', label: 'Email', target: () => emailInput.value })
const error = (field: string) =>
  state.value.errors.find((error) => error.field === field)?.message ?? ''
async function submit() {
  const result = await form.validate(async () => [
    ...(!name.value.trim()
      ? [{ field: 'name', message: pt.value ? 'Informe seu nome.' : 'Enter your name.' }]
      : []),
    ...(!email.value.includes('@')
      ? [{ field: 'email', message: pt.value ? 'Revise seu email.' : 'Check your email.' }]
      : []),
  ])
  saved.value = result === 'valid'
  if (result === 'invalid') await form.focusFirstError()
}
function edit() {
  saved.value = false
  form.invalidate()
}
</script>
<template>
  <m-column gap="lg">
    <m-form-errors :form="form" :title="t(pt ? 'Revise seus dados' : 'Review your details')" />
    <m-form-group
      :label="t(pt ? 'Vamos manter contato' : 'Let’s stay in touch')"
      :description="
        t(
          pt
            ? 'Seus dados permanecem nesta demonstração.'
            : 'Your details stay in this demonstration.',
        )
      "
    >
      <m-input
        ref="nameInput"
        v-model="name"
        :label="t(pt ? 'Nome' : 'Name')"
        autocomplete="name"
        :error="t(error('name'))"
        @update:modelValue="edit"
      />
      <m-input
        ref="emailInput"
        v-model="email"
        :label="t('Email')"
        type="email"
        autocomplete="email"
        :error="t(error('email'))"
        @update:modelValue="edit"
      />
    </m-form-group>
    <m-button :loading="state.validating" @click="submit">{{
      t(pt ? 'Revisar cadastro' : 'Review registration')
    }}</m-button>
    <m-text v-if="saved" tone="primary">{{
      t(pt ? 'Tudo certo para continuar.' : 'Ready to continue.')
    }}</m-text>
  </m-column>
</template>

Clearing the last error makes the summary leave and collapse. During that brief exit its old entries are hidden from assistive technology.

Desktop ​

On the desktop each error is a button that moves the keyboard to the field it names, and with announce the system reads the summary aloud when it changes. An error whose field is not registered is shown but cannot be chosen; see Desktop components.

Components for NativeScript and Web. Starting with Vue.