Skip to content

Form

High performance subscription-based form state management.

When To Use

  • When you need to create an instance to collect data.
  • When you need to validate fields in certain rules.

Examples

Basic

vue
<template>
  <a-form
    :model="formState"
    name="basic"
    :label-col="{ span: 8 }"
    :wrapper-col="{ span: 16 }"
    autocomplete="off"
    @finish="onFinish"
    @finishFailed="onFinishFailed"
  >
    <a-form-item
      label="Username"
      name="username"
      :rules="[{ required: true, message: 'Please input your username!' }]"
    >
      <a-input v-model:value="formState.username" />
    </a-form-item>

    <a-form-item
      label="Password"
      name="password"
      :rules="[{ required: true, message: 'Please input your password!' }]"
    >
      <a-input-password v-model:value="formState.password" />
    </a-form-item>

    <a-form-item name="remember" :wrapper-col="{ offset: 8, span: 16 }">
      <a-checkbox v-model:checked="formState.remember">Remember me</a-checkbox>
    </a-form-item>

    <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
      <a-button type="primary" html-type="submit">Submit</a-button>
    </a-form-item>
  </a-form>
</template>

<script setup>
import { reactive } from 'vue'

const formState = reactive({
  username: '',
  password: '',
  remember: true,
})

const onFinish = (values) => {
  console.log('Success:', values)
}

const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
</script>

Form Layout

vue
<template>
  <div>
    <a-form
      :layout="formLayout"
      :model="formState"
      name="basic"
      autocomplete="off"
      @finish="onFinish"
    >
      <a-form-item label="Form Layout" name="layout">
        <a-radio-group v-model:value="formLayout">
          <a-radio-button value="horizontal">Horizontal</a-radio-button>
          <a-radio-button value="vertical">Vertical</a-radio-button>
          <a-radio-button value="inline">Inline</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="Field A">
        <a-input v-model:value="formState.fieldA" placeholder="input placeholder" />
      </a-form-item>
      <a-form-item label="Field B">
        <a-input v-model:value="formState.fieldB" placeholder="input placeholder" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">Submit</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'

const formLayout = ref('horizontal')
const formState = reactive({
  fieldA: '',
  fieldB: '',
})

const onFinish = (values) => {
  console.log('Success:', values)
}
</script>

Form Validation

vue
<template>
  <a-form
    ref="formRef"
    :model="formState"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
  >
    <a-form-item ref="name" label="Activity name" name="name">
      <a-input v-model:value="formState.name" />
    </a-form-item>
    <a-form-item label="Activity zone" name="region">
      <a-select
        v-model:value="formState.region"
        placeholder="please select your zone"
      >
        <a-select-option value="shanghai">Zone one</a-select-option>
        <a-select-option value="beijing">Zone two</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="Activity time" required name="date1">
      <a-date-picker
        v-model:value="formState.date1"
        show-time
        type="date"
        placeholder="Pick a date"
        style="width: 100%;"
      />
    </a-form-item>
    <a-form-item label="Instant delivery" name="delivery">
      <a-switch v-model:checked="formState.delivery" />
    </a-form-item>
    <a-form-item label="Activity type" name="type">
      <a-checkbox-group v-model:value="formState.type">
        <a-checkbox value="1" name="type">Online</a-checkbox>
        <a-checkbox value="2" name="type">Promotion</a-checkbox>
        <a-checkbox value="3" name="type">Offline</a-checkbox>
      </a-checkbox-group>
    </a-form-item>
    <a-form-item label="Resources" name="resource">
      <a-radio-group v-model:value="formState.resource">
        <a-radio value="1">Sponsor</a-radio>
        <a-radio value="2">Venue</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item label="Activity form" name="desc">
      <a-textarea v-model:value="formState.desc" />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" @click="onSubmit">Create</a-button>
      <a-button style="margin-left: 10px;" @click="resetForm">Reset</a-button>
    </a-form-item>
  </a-form>
</template>

<script setup>
import { ref, reactive, toRaw } from 'vue'

const formRef = ref()
const labelCol = { span: 4 }
const wrapperCol = { span: 14 }

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

const rules = {
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  region: [
    { required: true, message: 'Please select Activity zone', trigger: 'change' },
  ],
  date1: [
    { required: true, message: 'Please pick a date', trigger: 'change' },
  ],
  type: [
    {
      type: 'array',
      required: true,
      message: 'Please select at least one activity type',
      trigger: 'change',
    },
  ],
  resource: [
    { required: true, message: 'Please select activity resource', trigger: 'change' },
  ],
  desc: [
    { required: true, message: 'Please input activity form', trigger: 'blur' },
  ],
}

const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      console.log('values', formState, toRaw(formState))
    })
    .catch(error => {
      console.log('error', error)
    })
}

const resetForm = () => {
  formRef.value.resetFields()
}
</script>

API

Form

PropertyDescriptionTypeDefaultVersion
colonConfigure the default value of colon for Form.Item. Indicates whether the colon after the label is displayed (only effective when prop layout is horizontal)booleantrue
disabledSet form component disable, only available for antd componentsbooleanfalse
hideRequiredMarkHide required mark of all form itemsbooleanfalse
labelAlignThe text align of label of all itemsleft | rightright
labelColThe layout of label. You can set span offset to something like {span: 3, offset: 12} or sm: {span: 3, offset: 12} same as with <Col>object-
labelWrapwhether label can be wrapbooleanfalse
layoutForm layouthorizontal | vertical | inlinehorizontal
modelForm data objectobject-
nameForm name. Will be the prefix of Field idstring-
noStyleNo style for true, used as a pure field controlbooleanfalse
preserveKeep field value even when field removedbooleantrue
requiredMarkRequired mark style. Can use required mark or optional mark. You can not config to single Form.Item since this is a Form level configboolean | optionaltrue
rulesForm validation rulesobject-
scrollToFirstErrorAuto scroll to first failed field when submitboolean | optionsfalse
sizeSet field component size (antd components only)small | middle | large-
validateOnRuleChangewhether to trigger validation when the rules prop is changedbooleantrue
validateTriggerConfig field validate triggerstring | string[]change
wrapperColThe layout for input controls, same as labelColobject-

Form Events

Events NameDescriptionArgumentsVersion
finishTriggered after submitting the form and verifying data successfullyfunction(values)
finishFailedTriggered after submitting the form and verifying data failedfunction({ values, errorFields, outOfDate })
submitDefines a function that will be called if the form data is valid.function(e:Event)
validateTriggered after a form item is validatedfunction(name, status, errorMsgs)
valuesChangeTriggered when value of any form control is changedfunction(changedValues, allValues)

Form.Item

PropertyDescriptionTypeDefaultVersion
autoLinkAuto link formbooleantrue
colonUsed with label, whether to display : after label text.booleantrue
extraThe extra prompt message. It is similar to help. Usage example: to display error message and prompt message at the same timestring | slot-
hasFeedbackUsed with validateStatus, this option specifies the validation status icon. Recommended to be used only with Input.booleanfalse
helpThe prompt message. If not provided, the prompt message will be generated by the validation rule.string | slot-
htmlForSet sub label htmlForstring-
labelLabel textstring | slot-
labelAlignThe text align of labelleft | rightright
labelColThe layout of label. You can set span offset to something like {span: 3, offset: 12} or sm: {span: 3, offset: 12} same as with <Col>object-
nameField name, support arraystring | number | (string | number)[]-
requiredDisplay required style. It will be generated by the validation rulebooleanfalse
rulesRules for field validationobject | object[]-
tooltipConfig tooltip infostring | slot-
validateFirstWhether stop validate on first rule of error for this field.booleanfalse
validateStatusThe validation status. If not provided, it will be generated by validation rule. options: success warning error validatingstring-
validateTriggerWhen to validate the value of children nodestring | string[]change
wrapperColThe layout for input controls, same as labelColobject-

Released under the MIT License.