---
title: "useFormValidator"
description: "Vue composables for form validation with any Standard Schema library (Valibot, Zod, ArkType...) - useFormValidator and useFormField provide a flexible and typed approach to handle form validation in your Vue applications."
package: "maz-ui"
url: "https://maz-ui.com/composables/use-form-validator"
---

# useFormValidator

> Vue composables for form validation with any Standard Schema library (Valibot, Zod, ArkType...) - useFormValidator and useFormField provide a flexible and typed approach to handle form validation in your Vue applications.

- Package: `maz-ui`
- Import: `import { useFormValidator } from 'maz-ui/composables/useFormValidator'`
- Nuxt: auto-imported by `@maz-ui/nuxt`, no import needed in a Nuxt app
- Web: https://maz-ui.com/composables/use-form-validator

## Introduction

`useFormValidator` and `useFormField` are two Vue composables that work together to provide powerful form validation. They are **validation library agnostic**: any library implementing [Standard Schema](https://standardschema.dev) works out of the box, like [Valibot](https://valibot.dev), [Zod](https://zod.dev) or [ArkType](https://arktype.io). See Validation Libraries.

- **useFormValidator**: Initializes form validation for your entire form. Use it in your form's parent component.
- **useFormField**: Manages individual field validation states. Use it when you need fine-grained control over a field or when fields are in child components.

**When to use each:**

| Composable | Use When |
|------------|----------|
| `useFormValidator` only | Simple forms where all fields are in the same component |
| `useFormValidator` + `useFormField` | Fields in child components, or when using `eager`, `blur`, or `progressive` validation modes |

## Quick Start

Install the validation library of your choice (Valibot is used in most examples of this page):

```bash [valibot]
pnpm add valibot
```

```bash [zod]
pnpm add zod
```

```bash [arktype]
pnpm add arktype
```

Here's the simplest form you can create with `useFormValidator`:

```vue
<script lang="ts" setup>
import { useFormValidator } from 'maz-ui/composables'
import { pipe, string, email, nonEmpty, minLength } from 'valibot'

// 1. Define your validation schema
const schema = {
  email: pipe(string(), nonEmpty('Email is required'), email('Invalid email')),
  password: pipe(string(), nonEmpty('Password is required'), minLength(8, 'Min 8 characters')),
}

// 2. Initialize the form validator
const {
  model,           // Form data (reactive)
  errorMessages,   // First error message for each field
  fieldsStates,    // Detailed state of each field
  isSubmitting,    // Is the form being submitted?
  handleSubmit,    // Submit handler wrapper
} = useFormValidator({ schema })

// 3. Handle form submission
const onSubmit = handleSubmit((data) => {
  // Called only if the form is valid
  console.log('Form submitted:', data)
})
</script>

<template>
  <form @submit="onSubmit">
    <MazInput
      v-model="model.email"
      label="Email"
      :hint="errorMessages.email"
      :error="!!errorMessages.email"
      :success="fieldsStates.email.valid"
    />
    <MazInput
      v-model="model.password"
      label="Password"
      type="password"
      :hint="errorMessages.password"
      :error="!!errorMessages.password"
      :success="fieldsStates.password.valid"
    />
    <MazBtn type="submit" :loading="isSubmitting">
      Login
    </MazBtn>
  </form>
</template>
```

## Validation Libraries

`useFormValidator` relies on [Standard Schema](https://standardschema.dev), a common interface shared by the main validation libraries. Maz-UI does not ship any validation library: install the one you prefer and pass its schemas. Valibot, Zod and ArkType are declared as optional peer dependencies of `maz-ui`, so your package manager warns you if the installed version is not supported.

| Library | Supported versions |
|---------|--------------------|
| [Valibot](https://valibot.dev) | `>=1.0.0 <2.0.0` |
| [Zod](https://zod.dev) | `>=3.24.0 <5.0.0` (v3 and v4) |
| [ArkType](https://arktype.io) | `>=2.0.0 <3.0.0` |
| [Others](https://standardschema.dev/#what-schema-libraries-implement-the-spec) | Any library implementing Standard Schema V1 |

The `schema` option is always a **plain object** where each key is a field name and each value is a schema of your library. Do not wrap it with `object()` / `z.object()`.

### Same form, different libraries

```ts [valibot]
import { useFormValidator } from 'maz-ui/composables'
import { email, minLength, nonEmpty, pipe, string } from 'valibot'

const { model, errorMessages, handleSubmit } = useFormValidator({
  schema: {
    email: pipe(string(), nonEmpty('Email is required'), email('Invalid email')),
    password: pipe(string(), minLength(8, 'Min 8 characters')),
  },
})
```

```ts [zod]
import { useFormValidator } from 'maz-ui/composables'
import { z } from 'zod'

const { model, errorMessages, handleSubmit } = useFormValidator({
  schema: {
    email: z.string().min(1, 'Email is required').pipe(z.email('Invalid email')),
    password: z.string().min(8, 'Min 8 characters'),
  },
})
```

```ts [arktype]
import { type } from 'arktype'
import { useFormValidator } from 'maz-ui/composables'

const { model, errorMessages, handleSubmit } = useFormValidator({
  schema: {
    email: type('string.email'),
    password: type('string >= 8'),
  },
})
```

### Live example with Zod

```vue
<script lang="ts" setup>
import { useFormValidator } from 'maz-ui/composables'
import { z } from 'zod'

const schema = {
  username: z.string().min(1, 'Username is required').min(3, 'Min 3 characters'),
  age: z.number({ error: 'Age is required' }).min(18, 'Min 18').max(100, 'Max 100'),
}

const {
  model,
  errorMessages,
  fieldsStates,
  isSubmitting,
  handleSubmit,
} = useFormValidator({ schema })

const onSubmit = handleSubmit((data) => {
  // data is typed as { username: string, age: number }
  console.log('Form submitted:', data)
})
</script>

<template>
  <form @submit="onSubmit">
    <MazInput
      v-model="model.username"
      label="Username"
      :hint="errorMessages.username"
      :error="!!errorMessages.username"
      :success="fieldsStates.username.valid"
    />
    <MazInput
      v-model="model.age"
      label="Age"
      type="number"
      :hint="errorMessages.age"
      :error="!!errorMessages.age"
      :success="fieldsStates.age.valid"
    />
    <MazBtn type="submit" :loading="isSubmitting">
      Submit
    </MazBtn>
  </form>
</template>
```

### Mixing libraries

Each field is validated by its own schema, so you can mix libraries in the same form (useful during a progressive migration from one library to another):

```ts
import { useFormValidator } from 'maz-ui/composables'
import { email, pipe, string } from 'valibot'
import { z } from 'zod'

const { model } = useFormValidator({
  schema: {
    email: pipe(string(), email('Invalid email')),
    age: z.number().min(18, 'Min 18'),
  },
})
```

### Custom schema

You can also write your own validator by implementing the `StandardSchemaV1` interface (exported by `maz-ui/composables`). `validate` can be synchronous or return a `Promise`:

```ts
import type { StandardSchemaV1 } from 'maz-ui/composables'
import { useFormValidator } from 'maz-ui/composables'

const frenchZipCode: StandardSchemaV1<string, string> = {
  '~standard': {
    version: 1,
    vendor: 'my-app',
    validate: value =>
      typeof value === 'string' && /^\d{5}$/.test(value)
        ? { value }
        : { issues: [{ message: 'Invalid zip code' }] },
  },
}

const { model } = useFormValidator({
  schema: { zipCode: frenchZipCode },
})
```

### Good to know

- **Empty values**: `undefined` and `null` field values are validated as an empty string (`''`). To make a field required, use a length rule (`nonEmpty()` with Valibot, `.min(1)` with Zod). An optional field with a format rule (email, URL...) has to accept the empty string explicitly, for example `z.email().or(z.literal(''))` with Zod or `union([literal(''), pipe(string(), email())])` with Valibot.
- **Error messages**: `errorMessages` contains the message of the first issue of each field, whatever the library.
- **Issues type**: `errors` and `fieldsStates[field].errors` are typed as `ValidationIssues`, the Standard Schema issue shape (`message` and `path`). At runtime, they are the native issues of your library, so you can cast them to access library specific properties (for example `BaseIssue<unknown>` from Valibot or `z.core.$ZodIssue` from Zod).
- **Type inference**: the `model` type (input) and the `handleSubmit` payload type (output, after transformations) are inferred from the schemas whatever the library.

## Understanding Form State

`useFormValidator` returns several reactive values to help you manage your form:

| Property | Type | Description |
|----------|------|-------------|
| `model` | `Ref<Model>` | The form data object - bind this to your inputs with `v-model` |
| `isValid` | `ComputedRef<boolean>` | `true` when all fields pass validation |
| `isDirty` | `ComputedRef<boolean>` | `true` when any field has been modified from its initial value |
| `isSubmitting` | `Ref<boolean>` | `true` while the form is being submitted |
| `isSubmitted` | `Ref<boolean>` | `true` after the form has been submitted at least once |
| `errorMessages` | `ComputedRef<Record<string, string>>` | The first error message for each field (if any) |
| `errors` | `ComputedRef<Record<string, ValidationIssues>>` | All validation issues for each field |
| `fieldsStates` | `Ref<FieldsStates>` | Detailed state object for each field |
| `handleSubmit` | `Function` | Wrapper function for form submission |
| `validateForm` | `Function` | Manually trigger form validation |
| `resetForm` | `Function` | Reset the form to its initial state |
| `scrollToError` | `Function` | Scroll to the first field with an error |

### Field States

Each field in `fieldsStates` contains:

| Property | Type | Description |
|----------|------|-------------|
| `valid` | `boolean` | Field passes validation |
| `error` | `boolean` | Field has an error that should be displayed |
| `errors` | `ValidationIssues` | Array of all validation issues |
| `dirty` | `boolean` | Field value differs from initial value |
| `blurred` | `boolean` | Field has lost focus at least once |
| `validated` | `boolean` | Validation has run at least once |
| `validating` | `boolean` | Async validation is in progress |

```vue
<script lang="ts" setup>
import { useFormValidator } from 'maz-ui/composables'
import { pipe, string, number, nonEmpty, minLength, minValue, maxValue } from 'valibot'

const schema = {
  name: pipe(string(), nonEmpty('Required'), minLength(3, 'Min 3 characters')),
  age: pipe(number(), minValue(18, 'Min 18'), maxValue(100, 'Max 100')),
}

const {
  model,
  errorMessages,
  fieldsStates,
  isValid,
  isDirty,
  isSubmitted,
  handleSubmit,
} = useFormValidator({ schema })

const onSubmit = handleSubmit((data) => {
  console.log('Submitted:', data)
})
</script>

<template>
  <form @submit="onSubmit">
    <MazInput v-model="model.name" label="Name" />
    <MazInput v-model="model.age" label="Age" type="number" />
    <MazBtn type="submit">Submit</MazBtn>
  </form>

  <!-- Debug panel -->
  <pre>{{ { isValid, isDirty, isSubmitted } }}</pre>
  <pre>{{ fieldsStates }}</pre>
</template>
```

## Validation Modes

Validation modes control **when** validation runs and **when** errors are displayed. Choose the mode that best fits your UX needs.

| Mode | Validates On | Shows Errors | Best For |
|------|--------------|--------------|----------|
| `lazy` (default) | Value change | After change (if not empty) | Simple forms |
| `aggressive` | Immediately + every change | Always | Real-time feedback |
| `eager` | Blur, then on change | After first blur | Better UX |
| `blur` | Only on blur | After blur | Minimal interruption |
| `progressive` | Silently, shows on blur if invalid | After blur or validation | Optimal UX |

**Tip:**

For `eager`, `blur`, and `progressive` modes, you must use `useFormField` with the `ref` option or `validationEvents` to capture blur events.

### Lazy Mode (Default)

The default mode. Validates when field values change. Errors only appear if the field is not empty.

```vue
<script lang="ts" setup>
import { useFormValidator } from 'maz-ui/composables'
import { pipe, string, email, nonEmpty, minLength } from 'valibot'

const schema = {
  name: pipe(string(), nonEmpty('Required'), minLength(3, 'Min 3 characters')),
  email: pipe(string(), nonEmpty('Required'), email('Invalid email')),
}

const { model, errorMessages, fieldsStates, isSubmitting, handleSubmit } = useFormValidator({
  schema,
  options: {
    mode: 'lazy', // This is the default
    scrollToError: '.has-error-lazy',
  },
})

const onSubmit = handleSubmit((data) => {
  console.log('Submitted:', data)
})
</script>
```

### Aggressive Mode

Validates all fields immediately when the form is created and on every change. Errors are always displayed.

```vue
<script lang="ts" setup>
import { useFormValidator } from 'maz-ui/composables'
import { pipe, string, email, nonEmpty, minLength } from 'valibot'

const schema = {
  name: pipe(string(), nonEmpty('Required'), minLength(3, 'Min 3 characters')),
  email: pipe(string(), nonEmpty('Required'), email('Invalid email')),
}

const { model, errorMessages, fieldsStates, isSubmitting, handleSubmit } = useFormValidator({
  schema,
  options: {
    mode: 'aggressive', // Validates immediately
  },
})
</script>
```

### Eager Mode (Recommended)

Validates on blur first (if the field is not empty), then on every change. This provides a good balance between immediate feedback and not overwhelming the user.

**Warning:**

Requires `useFormField` with `ref` option or `validationEvents`.

```vue
<script lang="ts" setup>
import { useFormValidator, useFormField } from 'maz-ui/composables'
import { pipe, string, email, nonEmpty, minLength } from 'valibot'
import { useTemplateRef } from 'vue'

const schema = {
  name: pipe(string(), nonEmpty('Required'), minLength(3, 'Min 3 characters')),
  email: pipe(string(), nonEmpty('Required'), email('Invalid email')),
}

const { isSubmitting, handleSubmit, isValid } = useFormValidator({
  schema,
  options: {
    mode: 'eager',
    scrollToError: '.has-error-eager',
    identifier: 'form-eager',
  },
})

// useFormField for each field with ref for blur detection
const {
  value: name,
  hasError: nameHasError,
  errorMessage: nameError,
  isValid: nameValid,
} = useFormField<string>('name', {
  ref: useTemplateRef('nameRef'),
  formIdentifier: 'form-eager',
})

const {
  value: email,
  hasError: emailHasError,
  errorMessage: emailError,
  isValid: emailValid,
} = useFormField<string>('email', {
  ref: useTemplateRef('emailRef'),
  formIdentifier: 'form-eager',
})
</script>

<template>
  <form @submit="handleSubmit(onSubmit)">
    <MazInput
      ref="nameRef"
      v-model="name"
      label="Name"
      :hint="nameError"
      :error="nameHasError"
      :success="nameValid"
    />
    <MazInput
      ref="emailRef"
      v-model="email"
      label="Email"
      :hint="emailError"
      :error="emailHasError"
      :success="emailValid"
    />

    <MazBtn type="submit" :loading="isSubmitting" :disabled="!isValid">Submit</MazBtn>
  </form>
</template>
```

### Blur Mode

**Warning:**

Requires `useFormField` with `ref` option or `validationEvents`.

Validates only when the field loses focus. Errors are only shown after blur.

```vue
<script lang="ts" setup>
import { useFormValidator, useFormField } from 'maz-ui/composables'
import { pipe, string, email, nonEmpty, minLength } from 'valibot'
import { useTemplateRef } from 'vue'

const schema = {
  name: pipe(string(), nonEmpty('Required'), minLength(3, 'Min 3 characters')),
  email: pipe(string(), nonEmpty('Required'), email('Invalid email')),
}

const { isSubmitting, handleSubmit } = useFormValidator({
  schema,
  options: {
    mode: 'blur',
    identifier: 'form-blur',
  },
})

const { value: name, hasError, errorMessage, isValid } = useFormField<string>('name', {
  ref: useTemplateRef('nameRef'),
  formIdentifier: 'form-blur',
})

const { value: email, hasError: emailHasError, errorMessage: emailError, isValid: emailValid } = useFormField<string>('email', {
  ref: useTemplateRef('emailRef'),
  formIdentifier: 'form-blur',
})
</script>
```

### Progressive Mode

**Warning:**

Requires `useFormField` with `ref` option or `validationEvents`.

The most user-friendly mode. Validates silently in the background. Shows errors only on blur if the field is invalid. Once valid, it stays valid until it becomes invalid again.

```vue
<script lang="ts" setup>
import { useFormValidator, useFormField } from 'maz-ui/composables'
import { pipe, string, email, nonEmpty, minLength, boolean, literal } from 'valibot'
import { useTemplateRef } from 'vue'

const schema = {
  name: pipe(string(), nonEmpty('Required'), minLength(3, 'Min 3 characters')),
  email: pipe(string(), nonEmpty('Required'), email('Invalid email')),
  agree: pipe(boolean(), literal(true, 'You must agree')),
}

const { isSubmitting, handleSubmit } = useFormValidator({
  schema,
  options: {
    mode: 'progressive',
    identifier: 'form-progressive',
  },
})

const { value: name, hasError, errorMessage, isValid } = useFormField<string>('name', {
  ref: useTemplateRef('nameRef'),
  formIdentifier: 'form-progressive',
})
// ... same for other fields
</script>
```

## useFormField for Child Components

`useFormField` is essential when:
1. Your form fields are in child components
2. You need the `eager`, `blur`, or `progressive` validation modes
3. You want fine-grained control over individual field states

### Return Values

| Property | Type | Description |
|----------|------|-------------|
| `value` | `WritableComputedRef<T>` | The field value (use with `v-model`) |
| `hasError` | `ComputedRef<boolean>` | Field has an error that should be displayed |
| `errors` | `ComputedRef<ValidationIssues>` | All validation issues |
| `errorMessage` | `ComputedRef<string>` | First error message |
| `isValid` | `ComputedRef<boolean>` | Field passes validation |
| `isDirty` | `ComputedRef<boolean>` | Field has been modified |
| `isBlurred` | `ComputedRef<boolean>` | Field has lost focus |
| `isValidated` | `ComputedRef<boolean>` | Validation has run |
| `isValidating` | `ComputedRef<boolean>` | Async validation in progress |
| `mode` | `ComputedRef<string>` | The validation mode |
| `validationEvents` | `ComputedRef<object>` | Blur event handler for `v-bind` |

### Two Ways to Bind Validation Events

#### Option 1: Using `ref` (Recommended)

Pass a template ref to `useFormField`. It will automatically detect interactive elements and attach blur listeners.

The `ref` option is **reactive**: if the field is rendered conditionally (e.g. with `v-if`), the blur listeners are attached automatically as soon as the element appears in the DOM, and removed when it is unmounted. You don't need to handle anything special.

```vue
<script setup>
import { useFormField } from 'maz-ui/composables'
import { useTemplateRef } from 'vue'

const { value, errorMessage, hasError } = useFormField<string>('email', {
  ref: useTemplateRef('emailRef'),
  formIdentifier: 'my-form',
})
</script>

<template>
  <MazInput
    ref="emailRef"
    v-model="value"
    :hint="errorMessage"
    :error="hasError"
  />
</template>
```

Because it is reactive, the same code works even when the input is wrapped in a `v-if`:

```vue
<script setup>
import { useFormField } from 'maz-ui/composables'
import { useTemplateRef, ref } from 'vue'

const isVisible = ref(false)

const { value, errorMessage, hasError } = useFormField<string>('email', {
  ref: useTemplateRef('emailRef'),
  formIdentifier: 'my-form',
})
</script>

<template>
  <MazInput
    v-if="isVisible"
    ref="emailRef"
    v-model="value"
    :hint="errorMessage"
    :error="hasError"
  />
</template>
```

You can also pass a raw `HTMLElement` directly. In that case it won't be reactive, so the element must already exist in the DOM:

```ts
const { value } = useFormField<string>('email', {
  ref: document.querySelector('input'),
  formIdentifier: 'my-form',
})
```

#### Option 2: Using `validationEvents`

If your component emits a `blur` event, you can use `v-bind` with `validationEvents`.

```vue
<script setup>
import { useFormField } from 'maz-ui/composables'

const { value, errorMessage, hasError, validationEvents } = useFormField<string>('email', {
  formIdentifier: 'my-form',
})
</script>

<template>
  <MazInput
    v-model="value"
    v-bind="validationEvents"
    :hint="errorMessage"
    :error="hasError"
  />
</template>
```

## TypeScript Type Inference

The form model is automatically typed based on your schema, whatever the validation library:

```ts
const schema = {
  name: pipe(string(), nonEmpty()),
  age: pipe(number(), minValue(0)),
  email: pipe(string(), email()),
}

const { model } = useFormValidator({ schema })
// model.value is typed as: { name?: string, age?: number, email?: string }
```

For `useFormField`, specify the field type as a generic parameter:

```ts
// Specify the type for better type safety
const { value } = useFormField<string>('name', { formIdentifier: 'my-form' })
// value is typed as WritableComputedRef<string>
```

**Warning: Common TypeScript Errors**

If you get circular reference errors with `useTemplateRef`, use the classic `ref()` instead:

```ts
// May cause TypeScript errors
const { value: email } = useFormField<string>('email', {
  ref: useTemplateRef('emailRef'),
})

// Solution 1: Add generic to useTemplateRef
const { value: email } = useFormField<string>('email', {
  ref: useTemplateRef<HTMLInputElement>('emailRef'),
})

// Solution 2: Use classic ref
const emailRef = ref<HTMLInputElement>()
const { value: email } = useFormField<string>('email', {
  ref: emailRef,
})
```

## Async Validation

Async validations (like checking username availability) are supported by every library: Valibot's `pipeAsync` and `checkAsync`, Zod's async `refine`, etc. The example below uses Valibot, here is the Zod equivalent of the schema:

```ts
import { z } from 'zod'

const schema = {
  username: z
    .string()
    .min(1, 'Username is required')
    .min(3, 'Min 3 characters')
    .refine(async (value) => {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 2000))
      return value !== 'taken'
    }, 'Username is already taken'),
}
```

```vue
<script lang="ts" setup>
import { useFormValidator, useFormField } from 'maz-ui/composables'
import { pipeAsync, string, nonEmpty, minLength, checkAsync } from 'valibot'
import { useTemplateRef } from 'vue'

const schema = {
  username: pipeAsync(
    string(),
    nonEmpty('Username is required'),
    minLength(3, 'Min 3 characters'),
    checkAsync(async (value) => {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 2000))
      return value !== 'taken' // Return true if valid
    }, 'Username is already taken'),
  ),
}

const { isSubmitting, handleSubmit } = useFormValidator({
  schema,
  options: { mode: 'eager', identifier: 'form-async' },
})

const {
  value: username,
  hasError,
  errorMessage,
  isValid,
  isValidating, // Shows loading state during async validation
} = useFormField<string>('username', {
  ref: useTemplateRef('usernameRef'),
  formIdentifier: 'form-async',
})
</script>

<template>
  <MazInput
    ref="usernameRef"
    v-model="username"
    :hint="errorMessage"
    :error="hasError"
    :success="isValid"
    :loading="isValidating"
  />
</template>
```

## Throttling and Debouncing

For expensive validations (like API calls), use throttling or debouncing to limit how often validation runs.

| Option | Behavior | Default Time | Use Case |
|--------|----------|--------------|----------|
| `debouncedFields` | Waits until user stops typing | 300ms | Search fields, API calls |
| `throttledFields` | Runs at most once per interval | 1000ms | Rate-limited APIs |

```vue
<script lang="ts" setup>
import { useFormValidator } from 'maz-ui/composables'
import { pipe, string, number, nonEmpty, minLength, minValue } from 'valibot'

const schema = {
  name: pipe(string(), nonEmpty('Required'), minLength(3, 'Min 3 characters')),
  age: pipe(number('Must be a number'), minValue(18, 'Must be 18+')),
}

const { model, errorMessages, fieldsStates, isSubmitting, handleSubmit } = useFormValidator({
  schema,
  options: {
    debouncedFields: { name: 500 },   // Wait 500ms after typing stops
    throttledFields: { age: 1000 },   // Validate at most every 1000ms
    // Use `true` for default times: debouncedFields: { name: true } // 300ms
  },
})
</script>
```

## Reset Form

Use `resetForm()` to reset the form to its initial state, or set `resetOnSuccess` to automatically reset after successful submission.

```vue
<script lang="ts" setup>
import { useFormValidator } from 'maz-ui/composables'
import { pipe, string, number, nonEmpty, minLength, minValue } from 'valibot'

const schema = {
  name: pipe(string(), nonEmpty('Required'), minLength(3, 'Min 3 characters')),
  age: pipe(number(), minValue(18, 'Must be 18+')),
}

const { model, errorMessages, fieldsStates, isSubmitting, handleSubmit, resetForm } = useFormValidator({
  schema,
  defaultValues: { name: 'John', age: 25 },
  options: {
    resetOnSuccess: true, // Auto-reset after successful submission (default: true)
  },
})

const onSubmit = handleSubmit((data) => {
  console.log('Submitted:', data)
  // Form will auto-reset because resetOnSuccess: true
})

// Manual reset
function handleReset() {
  resetForm()
}
</script>
```

## Multiple Forms on Same Page

Use the `identifier` option to have multiple independent forms on the same page. Make sure to match the identifier in both `useFormValidator` and `useFormField`.

```vue
<script lang="ts" setup>
import { useFormValidator, useFormField } from 'maz-ui/composables'

// Form 1
const form1 = useFormValidator({
  schema: schema1,
  options: { identifier: 'login-form' },
})

// Form 2
const form2 = useFormValidator({
  schema: schema2,
  options: { identifier: 'register-form' },
})

// useFormField must use matching identifier
const { value: loginEmail } = useFormField<string>('email', {
  formIdentifier: 'login-form',
})

const { value: registerEmail } = useFormField<string>('email', {
  formIdentifier: 'register-form',
})
</script>
```

## Error Handling and scrollToError

### scrollToError

Automatically scroll to the first field with an error when validation fails:

```ts
const { handleSubmit } = useFormValidator({
  schema,
  options: {
    scrollToError: '.has-error', // CSS selector for error elements
    // scrollToError: false,     // Disable scrolling
  },
})
```

Add the matching class to your fields:

```html
<MazInput
  :class="{ 'has-error': hasError }"
  :error="hasError"
/>
```

### onError Callback

Handle validation failures with the `onError` callback:

```ts
const onSubmit = handleSubmit(
  (data) => {
    // Success callback
    console.log('Valid:', data)
  },
  '.has-error', // scrollToError selector (optional)
  {
    onError: ({ model, errorMessages, errors }) => {
      // Called when validation fails
      console.log('Validation failed:', errorMessages)
    },
  }
)
```

## Performance & Best Practices

### Performance Tips

1. **Use throttling/debouncing** for expensive validations (API calls, complex logic)
2. **Prefer `eager` or `progressive` modes** over `aggressive` for better performance
3. **Use `lazy` mode** for simple forms with minimal validation
4. **Avoid `aggressive` mode on large forms** - it validates every field on every change

### Common Patterns

#### Multiple Forms with Identifiers

```ts
const { handleSubmit } = useFormValidator({
  schema,
  options: { identifier: 'my-unique-form' },
})

const { value } = useFormField<string>('email', {
  formIdentifier: 'my-unique-form', // Must match!
})
```

#### Custom Interactive Elements

If your custom component isn't detected for blur events, add `data-interactive`:

```vue
<div data-interactive class="custom-input" tabindex="0">
  Custom Input
</div>
```

### Common Pitfalls

| Pitfall | Solution |
|---------|----------|
| Mismatched `formIdentifier` | Ensure `useFormField`'s `formIdentifier` matches `useFormValidator`'s `identifier` |
| Validation not triggering in eager/blur/progressive modes | Use `ref` option or `v-bind="validationEvents"` |
| TypeScript errors with `useTemplateRef` | Add generic type or use classic `ref()` |
| Field not found warning | Make sure the field name exists in your schema |

## API Reference

### useFormValidator

#### Parameters

```ts
useFormValidator<TSchema>({
  schema: TSchema,                                    // Object of Standard Schema field schemas: Valibot, Zod, ArkType... (required)
  model?: Ref<Model>,                                 // External model ref (optional)
  defaultValues?: DeepPartial<Model>,                 // Initial values (optional)
  options?: {
    mode?: 'lazy' | 'aggressive' | 'eager' | 'blur' | 'progressive', // Default: 'lazy'
    throttledFields?: Record<string, number | true>,  // Fields to throttle
    debouncedFields?: Record<string, number | true>,  // Fields to debounce
    scrollToError?: string | false,                   // CSS selector, default: '.has-field-error'
    identifier?: string | symbol,                     // Form identifier, default: 'main-form-validator'
    resetOnSuccess?: boolean,                         // Reset after submit, default: true
  }
})
```

#### Return Values

```ts
{
  identifier: string | symbol
  model: Ref<Model>
  isValid: ComputedRef<boolean>
  isDirty: ComputedRef<boolean>
  isSubmitting: Ref<boolean>
  isSubmitted: Ref<boolean>
  errors: ComputedRef<Record<string, ValidationIssues>>
  errorMessages: ComputedRef<Record<string, string | undefined>>
  fieldsStates: Ref<FieldsStates<Model>>
  validateForm: (setErrors?: boolean) => Promise<void[]>
  scrollToError: (selector?: string) => void
  resetForm: () => void
  handleSubmit: <Func>(
    successCallback: Func,
    scrollToError?: string | false,
    options?: { onError?: Function, resetOnSuccess?: boolean }
  ) => (event?: Event) => Promise<ReturnType<Func>>
}
```

### useFormField

#### Parameters

```ts
useFormField<FieldType>(
  name: string,                                      // Field name in schema (required)
  options?: {
    defaultValue?: FieldType,                         // Default value for this field
    mode?: 'lazy' | 'aggressive' | 'eager' | 'blur' | 'progressive', // Override form mode
    ref?: Ref<HTMLElement | ComponentInstance> | HTMLElement, // Reactive template ref (v-if friendly) or raw element
    formIdentifier?: string | symbol,                 // Must match useFormValidator's identifier
  }
)
```

#### Return Values

```ts
{
  value: WritableComputedRef<FieldType>
  hasError: ComputedRef<boolean>
  errors: ComputedRef<ValidationIssues>
  errorMessage: ComputedRef<string | undefined>
  isValid: ComputedRef<boolean>
  isDirty: ComputedRef<boolean>
  isBlurred: ComputedRef<boolean>
  isValidated: ComputedRef<boolean>
  isValidating: ComputedRef<boolean>
  mode: ComputedRef<string | undefined>
  validationEvents: ComputedRef<{ onBlur?: () => void }>
}
```

### Types

```ts
// Standard Schema issue (https://standardschema.dev)
interface ValidationIssue {
  readonly message: string
  readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }>
}

type ValidationIssues = ValidationIssue[]

interface FormValidatorOptions<Model> {
  mode?: 'eager' | 'lazy' | 'aggressive' | 'blur' | 'progressive'
  throttledFields?: Partial<Record<keyof Model, number | true>>
  debouncedFields?: Partial<Record<keyof Model, number | true>>
  scrollToError?: string | false
  identifier?: string | symbol
  resetOnSuccess?: boolean
}

interface FormFieldOptions<FieldType> {
  defaultValue?: FieldType
  mode?: 'eager' | 'lazy' | 'aggressive' | 'blur' | 'progressive'
  ref?: Ref<HTMLElement | ComponentInstance> | HTMLElement
  formIdentifier?: string | symbol
}

interface FieldState<FieldType> {
  valid: boolean
  error: boolean
  errors: ValidationIssues
  dirty: boolean
  blurred: boolean
  validated: boolean
  validating: boolean
  initialValue?: Readonly<FieldType>
  mode?: string
}
```

## Troubleshooting

### Type Errors with useTemplateRef

**Problem**: TypeScript circular reference errors when using `useTemplateRef`

**Solutions**:

```ts
// Solution 1: Add generic type
const { value } = useFormField<string>('email', {
  ref: useTemplateRef<HTMLInputElement>('emailRef'),
})

// Solution 2: Use classic ref
const emailRef = ref<HTMLInputElement>()
const { value } = useFormField<string>('email', { ref: emailRef })
```

### Validation Not Triggering

**Problem**: `eager`, `blur`, or `progressive` mode not validating

**Solution**: These modes require blur event detection. Use either:

```ts
// Option 1: ref option
const { value } = useFormField<string>('name', {
  ref: useTemplateRef('inputRef'),
})

// Option 2: validationEvents
const { value, validationEvents } = useFormField<string>('name')
// Then: v-bind="validationEvents" on your input
```

### Conditionally Rendered Fields (`v-if`)

The `ref` option is reactive, so a field wrapped in `v-if` works out of the box: blur listeners are attached as soon as the element is rendered and removed when it is unmounted.

If blur validation still doesn't trigger:
1. Ensure the `ref` is bound to an HTML element or a Vue component exposing `$el`
2. For custom components, add the `data-interactive` attribute

### Mismatched Form Identifiers

**Problem**: `useFormField` not finding the form context

**Solution**: Ensure identifiers match:

```ts
// In parent
const { handleSubmit } = useFormValidator({
  schema,
  options: { identifier: 'my-form' }, // This identifier...
})

// In child
const { value } = useFormField<string>('email', {
  formIdentifier: 'my-form', // ...must match this one
})
```
