Form

Form

출처: 문서

본문

Form은 input, radio, select, checkbox 등으로 구성돼요. Form을 사용하면 데이터를 수집하고, 검증하고, 제출할 수 있어요.

TIP

이 컴포넌트는 기존 float 레이아웃을 대체하는 flex 레이아웃으로 업그레이드되었어요.

기본 폼 (Basic Form)

input, select, radio, checkbox 등 모든 종류의 입력 항목을 포함해요. 각 폼 컴포넌트 안에는 입력 항목의 컨테이너가 되는 form-item 필드가 하나 필요해요. label로 라벨을, prop으로 검증 대상 키를 지정해요.

활동 존, 활동 시간, 즉시 배송, 활동 유형, 리소스, 활동 형태 같은 라벨과 입력 필드를 이렇게 배치할 수 있어요.

TIP

W3C 규정

폼에 단일 줄 텍스트 입력 필드가 하나만 있으면, 사용자 에이전트(브라우저)가 그 필드에서 Enter를 폼 제출 요청으로 받아들여요. 이 동작을 막으려면 <el-form>에 @submit.prevent를 추가하면 돼요.

인라인 폼 (Inline Form)

세로 공간이 제한되어 있고 폼이 비교적 단순할 때 한 줄로 배치할 수 있어요. inline 속성을 true로 설정하면 폼이 인라인으로 표시돼요.

정렬 (Alignment)

디자인에 따라 라벨 요소를 정렬하는 여러 방법이 있어요. el-form-item의 label-position을 2.7.7부터 개별 설정할 수 있어요. 값이 비어 있으면 el-form의 label-position이 사용돼요. label-position 속성은 라벨이 어떻게 정렬될지 결정하고, top 또는 left가 될 수 있어요. top으로 설정하면 라벨이 폼 필드의 위쪽에 배치돼요.

검증 (Validation)

Form 컴포넌트는 데이터를 검증해서 오류를 찾고 고치는 데 도움을 줘요. Form 컴포넌트에 rules 속성을 추가하고 검증 규칙을 넘기며, FormItem에 prop 속성을 검증해야 할 특정 키로 설정하면 돼요. 더 자세한 내용은 async-validator에서 확인할 수 있어요.

import type { FormInstance, FormRules } from 'element-plus'

const ruleFormRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  name: [{ required: true, message: 'Please input Activity name', trigger: 'blur' }],
  // ...
})

커스텀 검증 규칙 (Custom Validation Rules)

이 예시는 2단계 비밀번호 검증을 완성하기 위해 자신만의 검증 규칙을 커스터마이즈하는 방법을 보여줘요. 여기서는 status-icon을 사용해 검증 결과를 아이콘으로 반영해요.

Confirm

Age

Submit Reset

TIP

커스텀 validate 콜백 함수는 반드시 호출해야 해요. 더 고급 사용법은 async-validator를 참고하세요.

Form Item 추가/삭제 (Add/Delete Form Item)

모든 검증 규칙을 한 번에 폼 컴포넌트에 전달하는 것 외에도, 단일 폼 필드에 검증 규칙을 동적으로 전달하거나 삭제할 수 있어요. clearValidate, resetField 등을 동적 규칙과 함께 사용할 수 있어요.

숫자 검증 (Number Validate)

숫자 검증에는 input v-model 바인딩에 .number 수정자가 추가되어야 해요. 이것은 Vue가 제공하는 문자열 값을 숫자로 변환하는 데 사용돼요.

TIP

el-form-item이 다른 el-form-item 안에 중첩되어 있으면 그 라벨 너비는 0이 돼요. 필요하면 그 el-form-item에 label-width를 설정할 수 있어요.

크기 제어 (Size Control)

Form 안의 모든 컴포넌트는 Form에서 size 속성을 상속받아요. 마찬가지로 FormItem에도 size 속성이 있어요. 특정 컴포넌트가 Form이나 FormItem에서 크기를 상속받지 않게 하고 싶다면 각 컴포넌트의 size를 세밀하게 조정할 수 있어요.

<template>
  <div>
    <el-form :label-position="labelPosition" :label-width="labelWidth" :size="size">
      <!-- form fields -->
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'

import type { ComponentSize, FormProps } from 'element-plus'

const size = ref('default')
const labelPosition = ref('right')

const sizeForm = reactive({
  name: '',
  region: '',
  date1: '',
  date2: '',
  delivery: false,
  type: [],
  resource: '',
  desc: '',
})

function onSubmit() {
  console.log('submit!')
}
</script>
.el-radio-group {
  margin-right: 12px;
}

접근성 (Accessibility)

el-form-item 안에 단일 입력(또는 select, checkbox 같은 관련 컨트롤)만 있을 때, 그 폼 항목의 라벨은 자동으로 해당 입력에 연결돼요. 하지만 el-form-item 안에 여러 입력이 있으면 폼 항목에는 대신 WAI-ARIA role of group이 할당돼요. 이 경우 개별 입력에 보조 라벨을 지정하는 것은 사용자의 책임이에요.

결국 여러 입력이 한 그룹을 이루면 "Your Information" 같은 라벨이 그 입력 그룹의 라벨 역할을 해요. 각 개별 입력에는 반드시 라벨을 지정해야 해요. placeholder는 "label" 속성의 대체가 아니에요.

Form API

Form Attributes

Name Description Type Default
model Data of form component. object —
rules Validation rules of form. object —
inline Whether the form is inline. boolean false
label-position Position of label. If set to 'left' or 'right', label-width prop is also required. enum right
label-width Width of label, e.g. '50px'. All its direct child form items will inherit this value. auto is supported. string / number ''
label-suffix Suffix of the label. string ''
hide-required-asterisk Whether to hide required fields should have a red asterisk (star) beside their labels. boolean false
require-asterisk-position Position of asterisk. enum left
show-message Whether to show the error message. boolean true
inline-message Whether to display the error message inline with the form item. boolean false
status-icon Whether to display an icon indicating the validation result. boolean false
validate-on-rule-change Whether to trigger validation when the rules prop is changed. boolean true
size Control the size of components in this form. enum —
disabled Whether to disable all components in this form. Before 2.12.0, if set to true, it will override the disabled prop of the inner component. After 2.12.0, the configuration of the internal components takes precedence. boolean false
scroll-to-error When validation fails, scroll to the first error form entry. boolean false
scroll-into-view-options 2.3.2 When validation fails, it scrolls to the first error item based on the scrollIntoView option. scrollIntoView. object / boolean true

Form Events

Name Description Type
validate triggers after a form item is validated Function

Form Slots

Name Description Subtags
default customize default content FormItem

Form Exposes

Name Description Type
validate Validate the whole form. Receives a callback or returns Promise. Function
validateField Validate specified fields. Function
resetFields Reset specified fields and remove validation result. Function
scrollToField Scroll to the specified fields. Function
clearValidate Clear validation messages for all or specified fields. Function
fields 2.7.3 Get all fields context. array
getField 2.10.2 Get a field context. Function
setInitialValues 2.13.1 Set initial values for form fields. When resetFields is called, fields will reset to these values. Function

FormItem API

FormItem Attributes

Name Description Type Default
prop A key of model. It could be a path of the property (e.g a.b.0 or ['a', 'b', '0']). In the use of validate and resetFields method, the attribute is required. string / string[] —
label Label text. string —
label-position 2.7.7 Position of item label. If set to 'left' or 'right', label-width prop is also required. Default extend label-position of form. enum ''
label-width Width of label, e.g. '50px'. 'auto' is supported. string / number —
required Whether the field is required or not, will be determined by validation rules if omitted. boolean —
rules Validation rules of form, see the following table, more advanced usage at async-validator. object —
error Field error message, set its value and the field will validate error and show this message immediately. string —
show-message Whether to show the error message. boolean true
inline-message Inline style validate message. boolean false
size Control the size of components in this form-item. enum —
for Same as for in native label. string —
validate-status Validation state of formItem. enum —

FormItemRule

Name Description Type Default
trigger How the validator is triggered. enum —

TIP

input 이벤트 기반으로 validator가 트리거되는 것을 원하지 않으면, 해당하는 입력 타입 컴포넌트(<el-input>, <el-radio>, <el-select>, ...)에 validate-event 속성을 false로 설정하면 돼요.

FormItem Slots

Name Description Type
default Content of Form Item. —
label Custom content to display on label. object
error Custom content to display validation message. object

FormItem Exposes

Name Description Type
size Form item size. object
validateMessage Validation message. object
validateState Validation state. object
validate Validate form item. Function
resetField Reset current field and remove validation result. Function
clearValidate Remove validation status of the field. Function
setInitialValue 2.13.1 Set initial value for this field. When resetField is called, the field will reset to this value. Function

Type Declarations

type Arrayable<T> = T | T[]

type FormValidationResult = Promise<boolean>

// ValidateFieldsError: see [async-validator](https://github.com/yiminghe/async-validator/blob/master/src/interface.ts)
type FormValidateCallback = (
  isValid: boolean,
  invalidFields?: ValidateFieldsError
) => Promise<void> | void

// RuleItem: see [async-validator](https://github.com/yiminghe/async-validator/blob/master/src/interface.ts)
interface FormItemRule extends RuleItem {
  trigger?: Arrayable<string>
}

type Primitive = null | undefined | string | number | boolean | symbol | bigint
type BrowserNativeObject = Date | FileList | File | Blob | RegExp
type IsTuple<T extends ReadonlyArray<any>> = number extends T['length']
  ? false
  : true
type ArrayMethodKey = keyof any[]
type TupleKey<T extends ReadonlyArray<any>> = Exclude<keyof T, ArrayMethodKey>
type ArrayKey = number
type PathImpl<K extends string | number, V, T extends ReadonlyArray<any>> = V extends
  Primitive | BrowserNativeObject
  ? `${K}`
  : `${K}` | `${K}.${Path<T[number], T>}`
type Path<T, K extends keyof T = keyof T> =
  T extends ReadonlyArray<any>
    ? IsTuple<T> extends true
      ? {
          [K in TupleKey<T>]-?: PathImpl<K, T[K], T>
        }[TupleKey<T>]
      : PathImpl<ArrayKey, T[number], T>
    : {
        [K in keyof T]-?: PathImpl<K, T[K], T>
      }[keyof T]
type FieldPath<T extends object> = T extends object ? Path<T> : never
// MaybeRef: see [@vueuse/core](https://github.com/vueuse/vueuse/blob/main/packages/shared/utils/types.ts)
// UnwrapRef: see [vue](https://github.com/vuejs/core/blob/main/packages/reactivity/src/ref.ts)
type FormRules<T extends MaybeRef<Record<string, any> | string> = any> = Partial<
  Record<UnwrapRef<T> extends string ? UnwrapRef<T> : FieldPath<UnwrapRef<T>>,
    Arrayable<FormItemRule>>
>

type FormItemValidateState = (typeof formItemValidateStates)[number]
type FormItemProps = ExtractPropTypes<typeof formItemProps>

type FormItemContext = FormItemProps & {
  $el: HTMLDivElement | undefined
  size: ComponentSize
  validateMessage: string
  validateState: FormItemValidateState
  isGroup: boolean
  labelId: string
  inputIds: string[]
  hasLabel: boolean
  fieldValue: any
  propString: string
  addInputId: (id: string) => void
  removeInputId: (id: string) => void
  validate: (
    trigger: string,
    callback?: FormValidateCallback
  ) => FormValidationResult
  resetField(): void
  clearValidate(): void
  setInitialValue: (value: any) => void
}

더 알아보기 (Learn more)