본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

폼

원문 보기 위키 갱신

폼 (Form)

내장된 유효성 검사와 제출 처리를 지원하는 폼 컴포넌트예요. 표준 스키마(Standard Schema)를 지원하는 어떤 검증 라이브러리와도 함께 사용할 수 있습니다.

출처: Nuxt UI

본문

Form 컴포넌트를 사용하면 Standard Schema를 지원하는 어떤 검증 라이브러리(Valibot, Zod, Regle, Yup, Joi, Superstruct)나 직접 만든 검증 로직으로 폼 데이터를 검증할 수 있어요.

FormField 컴포넌트와 함께 작동해 폼 요소 주변에 오류 메시지를 자동으로 표시해 줍니다.

스키마 검증 (Schema validation)

두 개의 prop이 필요해요:

[!WARNING]

검증 라이브러리는 기본으로 포함되지 않으니, 필요에 맞는 라이브러리를 직접 설치해야 해요.

<script setup lang="ts">
import * as v from 'valibot'
import type { FormSubmitEvent } from '@nuxt/ui'

const schema = v.object({
  email: v.pipe(v.string(), v.email('Invalid email')),
  password: v.pipe(v.string(), v.minLength(8, 'Must be at least 8 characters'))
})

type Schema = v.InferOutput<typeof schema>

const state = reactive({
  email: '',
  password: ''
})

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}
</script>

<template>
  <UForm :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
    <UFormField label="Email" name="email">
      <UInput v-model="state.email" />
    </UFormField>

    <UFormField label="Password" name="password">
      <UInput v-model="state.password" type="password" />
    </UFormField>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>
<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent } from '@nuxt/ui'

const schema = z.object({
  email: z.email('Invalid email'),
  password: z.string('Password is required').min(8, 'Must be at least 8 characters')
})

type Schema = z.output<typeof schema>

const state = reactive<Partial<Schema>>({
  email: undefined,
  password: undefined
})

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}
</script>

<template>
  <UForm :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
    <UFormField label="Email" name="email">
      <UInput v-model="state.email" />
    </UFormField>

    <UFormField label="Password" name="password">
      <UInput v-model="state.password" type="password" />
    </UFormField>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>
<script setup lang="ts">
import { useRegle, type InferInput } from '@regle/core'
import { required, email, minLength, withMessage } from '@regle/rules'
import type { FormSubmitEvent } from '@nuxt/ui'

const { r$ } = useRegle({ email: '', password: '' }, {
  email: { required, email: withMessage(email, 'Invalid email') },
  password: { required, minLength: withMessage(minLength(8), 'Must be at least 8 characters') }
})

type Schema = InferInput<typeof r$>

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}
</script>

<template>
  <UForm :schema="r$" :state="r$.$value" class="space-y-4" @submit="onSubmit">
    <UFormField label="Email" name="email">
      <UInput v-model="r$.$value.email" />
    </UFormField>

    <UFormField label="Password" name="password">
      <UInput v-model="r$.$value.password" type="password" />
    </UFormField>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>
<script setup lang="ts">
import { object, string } from 'yup'
import type { InferType } from 'yup'
import type { FormSubmitEvent } from '@nuxt/ui'

const schema = object({
  email: string().email('Invalid email').required('Required'),
  password: string()
    .min(8, 'Must be at least 8 characters')
    .required('Required')
})

type Schema = InferType<typeof schema>

const state = reactive({
  email: undefined,
  password: undefined
})

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}
</script>

<template>
  <UForm :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
    <UFormField label="Email" name="email">
      <UInput v-model="state.email" />
    </UFormField>

    <UFormField label="Password" name="password">
      <UInput v-model="state.password" type="password" />
    </UFormField>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>
<script setup lang="ts">
import Joi from 'joi'
import type { FormSubmitEvent } from '@nuxt/ui'

const schema = Joi.object({
  email: Joi.string().required(),
  password: Joi.string()
    .min(8)
    .required()
})

const state = reactive({
  email: undefined,
  password: undefined
})

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<typeof state>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}
</script>

<template>
  <UForm :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
    <UFormField label="Email" name="email">
      <UInput v-model="state.email" />
    </UFormField>

    <UFormField label="Password" name="password">
      <UInput v-model="state.password" type="password" />
    </UFormField>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>
<script setup lang="ts">
import { object, string, nonempty, refine } from 'superstruct'
import type { Infer } from 'superstruct'
import type { FormSubmitEvent } from '@nuxt/ui'

const schema = object({
  email: nonempty(string()),
  password: refine(string(), 'Password', (value) => {
    if (value.length >= 8) return true
    return 'Must be at least 8 characters'
  })
})

const state = reactive({
  email: '',
  password: ''
})

type Schema = Infer<typeof schema>

async function onSubmit(event: FormSubmitEvent<Schema>) {
  console.log(event.data)
}
</script>

<template>
  <UForm :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
    <UFormField label="Email" name="email">
      <UInput v-model="state.email" />
    </UFormField>

    <UFormField label="Password" name="password">
      <UInput v-model="state.password" type="password" />
    </UFormField>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>

커스텀 검증 (Custom validation)

validate prop을 사용해 직접 만든 검증 로직을 적용할 수 있어요.

검증 함수는 다음 속성을 가진 오류 목록을 반환해야 합니다:

  • message - 표시할 오류 메시지예요.
  • name - 오류를 보낼 FormField의 name이에요.

[!TIP]

복잡한 사용 사례를 처리하기 위해 schema prop과 함께 사용할 수도 있어요.

<script setup lang="ts">
import type { FormError, FormSubmitEvent } from '@nuxt/ui'

const state = reactive({
  email: undefined,
  password: undefined
})

type Schema = typeof state

function validate(state: Partial<Schema>): FormError[] {
  const errors = []
  if (!state.email) errors.push({ name: 'email', message: 'Required' })
  if (!state.password) errors.push({ name: 'password', message: 'Required' })
  return errors
}

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}
</script>

<template>
  <UForm :validate="validate" :state="state" class="space-y-4" @submit="onSubmit">
    <UFormField label="Email" name="email">
      <UInput v-model="state.email" />
    </UFormField>

    <UFormField label="Password" name="password">
      <UInput v-model="state.password" type="password" />
    </UFormField>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>

오류 보고 (Error reporting)

오류는 해당 FormField의 name prop을 통해 매칭돼요. email 필드의 오류는 <FormField name="email">에 표시됩니다.

중첩 필드는 점 표기법(dot notation)으로 매칭돼요. { user: z.object({ email: z.string() }) } 같은 스키마는 <FormField name="user.email">에 적용됩니다.

[!WARNING]

배열 항목의 오류는 이름에 인덱스를 포함하므로(예: tags.0, tags.1) name만으로는 <FormField name="tags">와 매칭되지 않아요. /^tags\..+/ 같은 정규식을 error-pattern prop에 사용해 잡아내야 합니다. 이는 InputTags 같은 컴포넌트에서 특히 유용해요.

<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent } from '@nuxt/ui'

const schema = z.object({
  email: z.email('Invalid email'),
  tags: z.array(z.string().regex(/^[a-z-]+$/, 'Lowercase letters and dashes only')).min(1, 'Please add at least one tag')
})

type Schema = z.output<typeof schema>

const state = reactive<Partial<Schema>>({
  email: undefined,
  tags: []
})

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}
</script>

<template>
  <UForm :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
    <UFormField label="Email" name="email">
      <UInput v-model="state.email" />
    </UFormField>

    <UFormField label="Tags" name="tags" :error-pattern="/^tags\..+/">
      <UInputTags v-model="state.tags" />
    </UFormField>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>

입력 이벤트 (Input events)

Form 컴포넌트는 입력이 input, change, 또는 blur 이벤트를 방출할 때 자동으로 검증을 실행해요.

  • input에서의 검증은 입력하는 동안 발생해요.
  • change에서의 검증은 값을 확정할 때 발생해요.
  • blur에서의 검증은 입력이 포커스를 잃을 때 발생해요.

validate-on prop으로 검증 시점을 제어할 수 있어요.

[!TIP]

폼은 항상 제출 시 검증합니다.

<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent } from '@nuxt/ui'

const schema = z.object({
  input: z.string({ message: 'Please enter your email' }).min(10, 'Must be at least 10 characters'),
  inputNumber: z.number({ message: 'Please enter a number' }).min(10, 'Must be at least 10'),
  inputMenu: z.any().refine(option => option?.value === 'option-2', {
    message: 'Please select Option 2'
  }),
  inputMenuMultiple: z.any().refine(values => !!values?.find((option: any) => option.value === 'option-2'), {
    message: 'Option 2 must be included'
  }),
  textarea: z.string({ message: 'Please enter a message' }).min(10, 'Must be at least 10 characters'),
  select: z.string({ message: 'Please select an option' }).refine(value => value === 'option-2', {
    message: 'Please select Option 2'
  }),
  selectMultiple: z.array(z.string(), { message: 'Please select at least one option' }).refine(values => values.includes('option-2'), {
    message: 'Option 2 must be included'
  }),
  selectMenu: z.any().refine(option => option?.value === 'option-2', {
    message: 'Please select Option 2'
  }),
  selectMenuMultiple: z.any().refine(values => !!values?.find((option: any) => option.value === 'option-2'), {
    message: 'Option 2 must be included'
  }),
  switch: z.boolean().refine(value => value === true, {
    message: 'Must be enabled'
  }),
  checkbox: z.boolean().refine(value => value === true, {
    message: 'Must be checked'
  }),
  radioGroup: z.string({ message: 'Please select an option' }).refine(value => value === 'option-2', {
    message: 'Please select Option 2'
  }),
  checkboxGroup: z.any().refine(values => !!values?.find((option: any) => option === 'option-2'), {
    message: 'Option 2 must be included'
  }),
  listbox: z.any().refine(option => option?.value === 'option-2', {
    message: 'Please select Option 2'
  }),
  listboxMultiple: z.any().refine(values => !!values?.find((option: any) => option.value === 'option-2'), {
    message: 'Option 2 must be included'
  }),
  inputTags: z.array(z.string(), { message: 'Please add at least one tag' }).min(1, 'Please add at least one tag'),
  inputDate: z.any().refine(value => !!value, {
    message: 'Please select a date'
  }),
  inputTime: z.any().refine(value => !!value, {
    message: 'Please select a time'
  }),
  slider: z.number().min(1, 'Must be greater than 0').max(20, 'Must be less than 20'),
  rating: z.number().min(1, 'Please select a rating'),
  pin: z.string().regex(/^\d$/, 'Must be a digit').array().length(5, 'All 5 digits are required'),
  file: z.file({ message: 'Please upload a file' }).min(1, 'File is required').max(1024 * 1024, 'File must be less than 1MB').mime('image/png', 'Only PNG images are allowed')
})

type Schema = z.input<typeof schema>

const state = reactive<Partial<Schema>>({
  switch: false,
  checkbox: false,
  slider: 0,
  rating: 0,
  pin: []
})

const form = useTemplateRef('form')

const items = [
  { label: 'Option 1', value: 'option-1' },
  { label: 'Option 2', value: 'option-2' },
  { label: 'Option 3', value: 'option-3' }
]

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}
</script>

<template>
  <UForm ref="form" :state="state" :schema="schema" class="w-full" @submit="onSubmit">
    <div class="grid sm:grid-cols-2 md:grid-cols-3 gap-4">
      <UFormField label="Input" name="input">
        <UInput v-model="state.input" placeholder="you@example.com" class="w-full" />
      </UFormField>

      <UFormField name="inputNumber" label="InputNumber">
        <UInputNumber v-model="state.inputNumber" placeholder="Enter a number" class="w-full" />
      </UFormField>

      <UFormField name="pin" label="PinInput" :error-pattern="/(pin)\..*/">
        <UPinInput v-model="state.pin" placeholder="○" />
      </UFormField>

      <UFormField name="inputDate" label="InputDate">
        <UInputDate v-model="state.inputDate" class="w-full" />
      </UFormField>

      <UFormField name="inputTime" label="InputTime">
        <UInputTime v-model="state.inputTime" class="w-full" />
      </UFormField>

      <UFormField name="inputTags" label="InputTags">
        <UInputTags v-model="state.inputTags" placeholder="Add a tag..." class="w-full" />
      </UFormField>

      <UFormField name="inputMenu" label="InputMenu">
        <UInputMenu v-model="state.inputMenu" :items="items" placeholder="Search an option..." class="w-full" />
      </UFormField>

      <UFormField name="inputMenuMultiple" label="InputMenu (Multiple)">
        <UInputMenu v-model="state.inputMenuMultiple" multiple :items="items" placeholder="Search options..." class="w-full" />
      </UFormField>

      <UFormField label="Textarea" name="textarea">
        <UTextarea v-model="state.textarea" placeholder="Write your message..." class="w-full" :rows="1" />
      </UFormField>

      <UFormField name="select" label="Select">
        <USelect v-model="state.select" :items="items" placeholder="Choose an option" class="w-full" />
      </UFormField>

      <UFormField name="selectMultiple" label="Select (Multiple)">
        <USelect v-model="state.selectMultiple" multiple :items="items" placeholder="Choose options" class="w-full" />
      </UFormField>

      <div class="hidden md:block" />

      <UFormField name="selectMenu" label="SelectMenu">
        <USelectMenu v-model="state.selectMenu" :items="items" placeholder="Search an option..." class="w-full" />
      </UFormField>

      <UFormField name="selectMenuMultiple" label="SelectMenu (Multiple)">
        <USelectMenu v-model="state.selectMenuMultiple" multiple :items="items" placeholder="Search options..." class="w-full" />
      </UFormField>

      <div class="hidden md:block" />

      <UFormField name="listbox" label="Listbox">
        <UListbox v-model="state.listbox" :items="items" class="w-full" />
      </UFormField>

      <UFormField name="listboxMultiple" label="Listbox (Multiple)">
        <UListbox v-model="state.listboxMultiple" :items="items" multiple class="w-full" />
      </UFormField>

      <UFormField name="file" label="FileUpload">
        <UFileUpload
          v-model="state.file"
          label="Drop your image here"
          description="PNG (max. 1MB)"
          class="w-full"
        />
      </UFormField>

      <UFormField name="checkbox" label="Checkbox">
        <UCheckbox v-model="state.checkbox" label="Check me" />
      </UFormField>

      <UFormField name="switch" label="Switch">
        <USwitch v-model="state.switch" label="Switch me" />
      </UFormField>

      <UFormField name="slider" label="Slider">
        <USlider v-model="state.slider" class="mt-2.5" />
      </UFormField>

      <UFormField name="rating" label="InputRating">
        <UInputRating v-model="state.rating" />
      </UFormField>

      <UFormField name="checkboxGroup">
        <UCheckboxGroup v-model="state.checkboxGroup" legend="CheckboxGroup" :items="items" />
      </UFormField>

      <UFormField name="radioGroup">
        <URadioGroup v-model="state.radioGroup" legend="RadioGroup" :items="items" />
      </UFormField>
    </div>

    <div class="flex gap-2 mt-8">
      <UButton type="submit">
        Submit
      </UButton>

      <UButton variant="outline" @click="form?.clear()">
        Clear
      </UButton>
    </div>
  </UForm>
</template>

[!TIP]

useFormField 컴포저블을 사용해 자신의 컴포넌트 안에서 이 기능을 구현할 수도 있어요.

오류 이벤트 (Error event)

@error 이벤트를 수신해 오류를 처리할 수 있어요. 이 이벤트는 폼이 제출될 때 발생하며, 다음 필드를 가진 FormError 객체 배열을 포함합니다:

  • id - 입력의 id예요.
  • name - FormField의 name이에요.
  • message - 표시할 오류 메시지예요.

다음은 폼이 제출된 후 오류가 있는 첫 번째 입력 요소에 포커스를 맞추는 예시예요:

<script setup lang="ts">
import type { FormError, FormErrorEvent, FormSubmitEvent } from '@nuxt/ui'

const state = reactive({
  email: undefined,
  password: undefined
})

type Schema = typeof state

function validate(state: Partial<Schema>): FormError[] {
  const errors = []
  if (!state.email) errors.push({ name: 'email', message: 'Required' })
  if (!state.password) errors.push({ name: 'password', message: 'Required' })
  return errors
}

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}

async function onError(event: FormErrorEvent) {
  if (event?.errors?.[0]?.id) {
    const element = document.getElementById(event.errors[0].id)
    element?.focus()
    element?.scrollIntoView({ behavior: 'smooth', block: 'center' })
  }
}
</script>

<template>
  <UForm :validate="validate" :state="state" class="space-y-4" @submit="onSubmit" @error="onError">
    <UFormField label="Email" name="email">
      <UInput v-model="state.email" />
    </UFormField>

    <UFormField label="Password" name="password">
      <UInput v-model="state.password" type="password" />
    </UFormField>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>

HTML5 검증 4.5+ (HTML5 validation)

form.submit()을 프로그래매틱하게 호출하면 Form 컴포넌트가 제출 전에 네이티브 HTML5 검증을 자동으로 실행해요.

[!NOTE]

제출 버튼이 모달 푸터처럼 폼 요소 밖에 있을 때 특히 유용합니다.

<script setup lang="ts">
import type { FormSubmitEvent } from '@nuxt/ui'

const state = reactive({
  email: undefined,
  age: undefined
})

type Schema = typeof state

const form = useTemplateRef('form')

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}
</script>

<template>
  <div class="space-y-4">
    <UForm ref="form" :state="state" class="space-y-4" @submit="onSubmit">
      <UFormField label="Email" name="email">
        <UInput v-model="state.email" type="email" required />
      </UFormField>

      <UFormField label="Age" name="age">
        <UInput v-model="state.age" type="number" min="18" max="100" required />
      </UFormField>
    </UForm>

    <UButton @click="form?.submit()">
      Submit
    </UButton>
  </div>
</template>

폼 중첩 (Nesting forms)

nested prop을 사용해 여러 Form 컴포넌트를 중첩하고 검증 함수를 연결할 수 있어요. 이 경우 부모 폼을 검증하면 그 안의 다른 모든 폼도 자동으로 검증됩니다.

중첩 폼은 부모의 state를 직접 상속하므로 별도의 state를 정의할 필요가 없어요. name prop을 사용해 부모 state의 중첩 속성을 타깃할 수 있습니다.

사용자 입력에 따라 필드를 동적으로 추가할 때 사용할 수 있어요:

<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent } from '@nuxt/ui'

const schema = z.object({
  name: z.string().min(2),
  news: z.boolean().default(false)
})

type Schema = z.output<typeof schema>

const nestedSchema = z.object({
  email: z.email()
})

type NestedSchema = z.output<typeof nestedSchema>

const state = reactive<Partial<Schema & NestedSchema>>({ })

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}
</script>

<template>
  <UForm
    ref="form"
    :state="state"
    :schema="schema"
    class="gap-4 flex flex-col w-60"
    @submit="onSubmit"
  >
    <UFormField label="Name" name="name">
      <UInput v-model="state.name" placeholder="John Lennon" />
    </UFormField>

    <div>
      <UCheckbox v-model="state.news" name="news" label="Register to our newsletter" @update:model-value="state.email = undefined" />
    </div>

    <UForm v-if="state.news" :schema="nestedSchema" nested>
      <UFormField label="Email" name="email">
        <UInput v-model="state.email" placeholder="john@lennon.com" />
      </UFormField>
    </UForm>

    <div>
      <UButton type="submit">
        Submit
      </UButton>
    </div>
  </UForm>
</template>

또는 목록 입력을 검증하는 데 사용할 수 있어요:

<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent } from '@nuxt/ui'

const schema = z.object({
  customer: z.string().min(2)
})

type Schema = z.output<typeof schema>

const itemSchema = z.object({
  description: z.string().min(1),
  price: z.number().min(0)
})

type ItemSchema = z.output<typeof itemSchema>

const state = reactive<Partial<Schema & { items: Partial<ItemSchema>[] }>>({ })

function addItem() {
  if (!state.items) {
    state.items = []
  }
  state.items.push({})
}

function removeItem() {
  if (state.items) {
    state.items.pop()
  }
}

const toast = useToast()

async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Success', description: 'The form has been submitted.', color: 'success' })
  console.log(event.data)
}
</script>

<template>
  <UForm
    :state="state"
    :schema="schema"
    class="gap-4 flex flex-col w-60"
    @submit="onSubmit"
  >
    <UFormField label="Customer" name="customer">
      <UInput v-model="state.customer" placeholder="Wonka Industries" />
    </UFormField>

    <UForm
      v-for="item, count in state.items"
      :key="count"
      :name="`items.${count}`"
      :schema="itemSchema"
      class="flex gap-2"
      nested
    >
      <UFormField :label="!count ? 'Description' : undefined" name="description">
        <UInput v-model="item.description" />
      </UFormField>
      <UFormField :label="!count ? 'Price' : undefined" name="price" class="w-20">
        <UInput v-model="item.price" type="number" />
      </UFormField>
    </UForm>

    <div class="flex gap-2">
      <UButton color="neutral" variant="subtle" size="sm" @click="addItem()">
        Add Item
      </UButton>

      <UButton color="neutral" variant="ghost" size="sm" @click="removeItem()">
        Remove Item
      </UButton>
    </div>
    <div>
      <UButton type="submit">
        Submit
      </UButton>
    </div>
  </UForm>
</template>

API

Props

/**
 * Props for the Form component
 */
interface FormProps {
  id?: string | number | undefined;
  /**
   * Schema to validate the form state. Supports Standard Schema objects, Yup, Joi, and Superstructs.
   */
  schema?: S | undefined;
  /**
   * An object representing the current state of the form.
   */
  state?: N extends false ? Partial<InferInput<S>> : never | undefined;
  /**
   * Custom validation function to validate the form state.
   */
  validate?: (state: Partial<InferInput<S>>): FormError<string>[] | Promise<FormError<string>[]> | undefined;
  /**
   * The list of input events that trigger the form validation.
   * @default `['blur', 'change', 'input']`
   */
  validateOn?: FormInputEvents[] | undefined;
  /**
   * Disable all inputs inside the form.
   */
  disabled?: boolean | undefined;
  /**
   * The `name` attribute of the form element.
   * For nested forms (`nested` is true), this is also used as the path of the form's state within its parent form.
   */
  name?: string | undefined;
  /**
   * Delay in milliseconds before validating the form on input events.
   * @default 300
   */
  validateOnInputDelay?: number | undefined;
  /**
   * If true, applies schema transformations on submit.
   * @default true as T
   */
  transform?: T | undefined;
  /**
   * If true, this form will attach to its parent Form and validate at the same time.
   * @default `false`
   */
  nested?: N | undefined;
  /**
   * When `true`, all form elements will be disabled on `@submit` event.
   * This will cause any focused input elements to lose their focus state.
   * @default true
   */
  loadingAuto?: boolean | undefined;
  ui?: { base?: any; } | undefined;
  acceptcharset?: string | undefined;
  action?: string | undefined;
  autocomplete?: string | undefined;
  enctype?: string | undefined;
  method?: string | undefined;
  novalidate?: false | true | "true" | "false" | undefined;
  target?: string | undefined;
}

[!NOTE] See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attributes

이 컴포넌트는 모든 네이티브 <form> HTML 속성도 지원해요.

Slots

/**
 * Slots for the Form component
 */
interface FormSlots {
  default(): any;
}

Emits

/**
 * Emitted events for the Form component
 */
interface FormEmits {
  submit: (payload: [event: FormSubmitEvent<FormData<S, T>>]) => void;
  error: (payload: [event: FormErrorEvent]) => void;
}

Expose

useTemplateRef를 사용해 타입이 지정된 컴포넌트 인스턴스에 접근할 수 있어요.

<script setup lang="ts">
const form = useTemplateRef('form')
</script>

<template>
  <UForm ref="form" />
</template>

이렇게 하면 다음에 접근할 수 있습니다:

Name Type
submit() Promise<void>
Triggers form submission with HTML5 validation.
validate(opts: { name?: keyof T | (keyof T)[], silent?: boolean, nested?: boolean, transform?: boolean }) Promise<T>
Triggers form validation. Will raise any errors unless opts.silent is set to true.
clear(path?: keyof T | RegExp) void
Clears form errors associated with a specific path. If no path is provided, clears all form errors.
getErrors(path?: keyof T | RegExp) FormErrorWithId[]
Retrieves form errors associated with a specific path. If no path is provided, returns all form errors.
setErrors(errors: FormError[], name?: keyof T | RegExp) void
Sets form errors for a given path. If no path is provided, overrides all errors.
errors Ref<FormErrorWithId[]>
A reference to the array containing validation errors. Use this to access or manipulate the error information.
disabled Ref<boolean>
dirty Ref<boolean> true if at least one form field has been updated by the user.
dirtyFields ReadonlySet<DeepReadonly<keyof T>> Tracks fields that have been modified by the user.
touchedFields ReadonlySet<DeepReadonly<keyof T>> Tracks fields that the user interacted with.
blurredFields ReadonlySet<DeepReadonly<keyof T>> Tracks fields blurred by the user.

테마 (Theme)

export default defineAppConfig({
  ui: {
    form: {
      base: ''
    }
  }
})

변경 기록 (Changelog)

컴포넌트와 테마의 커밋 내역을 확인해 보세요.

더 알아보기 (Learn more)