---
title: "useAutoForm"
description: "A composable for creating typed Zod schemas and managing AutoForm controls."
canonical_url: "https://nuxt.mhaibaraai.cn/en/docs/composables/use-auto-form"
---
# useAutoForm

> A composable for creating typed Zod schemas and managing AutoForm controls.

## Usage

Use the auto-imported `useAutoForm` composable to create typed Zod schemas and provide validation rules and control configuration for the [`AutoForm`](https://nuxt.mhaibaraai.cn/docs/auto-form) component.

```vue
<script setup lang="ts">
const { afz } = useAutoForm()

const schema = afz.object({
  username: afz.string('Username is required'),
  email: afz.email('Please enter a valid email address'),
  age: afz.number().min(18, 'Must be at least 18 years old')
})

const formData = ref()
</script>

<template>
  <MAutoForm v-model="formData" :schema="schema" />
</template>
```

- `useAutoForm` returns the enhanced Zod factory object `afz`, which supports attaching AutoForm metadata to schemas.
- Metadata is automatically persisted through Zod's chained calls (e.g. `.optional()`, `.nullable()`, `.default()`, etc.).

> [!NOTE]
> 
> Schemas created with the 
> 
> afz
> 
>  factory intercept Zod's clone methods to ensure metadata is not lost during chained calls.

## Custom Control Registration

When using custom controls, define them with the `defineControl` helper:

```ts
const { afz, defineControl } = useAutoForm({
  myInput: defineControl({
    component: MyCustomInput,
    controlProps: { class: 'w-full' }
  })
})

// Now usable in a schema
const schema = afz.string({
  type: 'myInput',
  controlProps: { variant: 'outline' }
})
```

## API

### useAutoForm()

`useAutoForm(controls?: AutoFormControls): UseAutoFormReturn`

Creates an AutoForm factory and control manager.

#### Parameters

**controls** (`AutoFormControls`): Custom control mapping object used to extend or override default controls, defined with defineControl (see "Custom Control Registration" above).

#### Returns

**afz** (`TypedZodFactory`): Typed Zod factory object for creating schemas with metadata.

**defineControl** (`Function`): Helper function for defining controls.

**DEFAULT_CONTROLS** (`Object`): Default control mapping object.

**controls** (`Object`): The custom control mapping passed in.

**getAutoFormMetadata** (`Function`): Utility function to extract custom metadata from a schema.

## Changelog

See commit history for [src/runtime/composables/useAutoForm.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/useAutoForm.ts).


## Sitemap

See the full [sitemap](https://nuxt.mhaibaraai.cn/sitemap.md) for all pages.
