Form

High performance Form component with data scope management. Including data collection, verification, and styles.

Form

When to use

When you need to create an instance or collect information.
When you need to validate fields in certain rules.


Basic Usage

Basic Form data control. Includes layout, initial values, validation and submit.

Form methods

Call form method with Form.useForm.
Note that useForm is a React Hooks that only works in functional component.
Select an option

Form methods (Class component)

We recommend use Form.useForm to create data control. If you are using class component, you can get it by ref.
Select an option

Form Layout

There are three layout for form: horizontal, vertical, inline.

Required style

Switch required or optional style with requiredMark.

Dynamic Form Item

Add or remove form items dynamically. add function support config initial value.

Dynamic Form nest Items

Nest dynamic field need extends field. Pass field.name and field.fieldKey to nest item.

Complex Dynamic Form Item

This example demonstrates the case that a form contains multiple form controls.

Nest

name prop support nest data structure. Customize validate message template with validateMessages or message. Ref here about message template.

Complex form control

This demo show how to use Form.Item with multiple controls. <Form.Item name="field" /> will only bind control(Input/Select) which is the only children of it. Image this case, you add some text description after Input, then you have to wrap Input by a extra <Form.Item name="field">. style property of Form.Item/ could be useful to modify the nested form item layout, or <Form.Item noStyle /> turn it into a pure form bind component(like getFieldDecorator in 3.x).
- <Form.Item label="Field" name="field">
- <Input />
- </Form.Item>
+ <Form.Item label="Field">
+ <Form.Item name="field" noStyle><Input /></Form.Item> // that will bind input
+ <span>description</span>
+ </Form.Item>
This demo show three typical usages:• Username: extra elements after control, using <Form.Item name="field" noStyle /> inside Form.Item to bind Input.• Address: two controls in one line, using two <Form.Item name="field" noStyle /> to bind each control.• BirthDate:two controls in one line with indeptent error message, using two <Form.Item name="field" noStyle /> to bind each control, make layout inline by customizing style property.
Note, in this case, no more name property should be left in Form.Item with label.
See Customized Form Controls demo below for further advanced usage.
Select province

Customized Form Controls

Customized or third-party form controls can be used in Form, too. Controls must follow these conventions:
It has a controlled property value or other name which is equal to the value of valuePropName.
It has event onChange or an event which name is equal to the value of trigger.
RMB

Store Form Data into Upper Component

We can store form data into upper component or Redux or dva by using onFieldsChange and fields, see more at this rc-field-form demo.
Note: Save Form data globally is not a good practice. You should avoid this if not necessary.
[
  {
    "name": [
      "username"
    ],
    "value": "Store value"
  }
]

Control between forms

Use Form.Provider to process data between forms. In this case, submit button is in the Modal which is out of Form. You can use form.submit to submit form. Besides, we recommend native <Button htmlType="submit" /> to submit a form.
( No user yet. )

Inline Login Form

Inline login form is often used in navigation bar.

Login Form

Normal login form which can contain more elements.
Or

Registration

Fill in this form to create a new account for you.
Zhejiang / Hangzhou / West Lake
+86
We must make sure that your are a human.
Three columns layout is often used for advanced searching of data table.
Because the width of label is not fixed, you may need to adjust it by customizing its style.
Search Result List

Form in Modal to Create

When user visit a page with a list of items, and want to create a new item. The page can popup a form in Modal, then let user fill in the form to create an item.
The value of time-related components is a moment object, which we need to pre-process it before we submit to server.

Handle Form Data Manually

Form will collect and validate form data automatically. But if you don't need this feature or the default behavior cannot satisfy your business, you can handle form data manually.
A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Customized Validation

We provide properties like validateStatus help hasFeedback to customize your own validate status and message, without using Form.
1. validateStatus: validate status of form components which could be 'success', 'warning', 'error', 'validating'.
2. hasFeedback: display feed icon of input control
3. help: display validate message.
Should be combination of numbers & alphabets
The information is being validated...
Should be combination of numbers & alphabets
The information is being validated...
Please select the correct date
-

Dynamic Rules

Perform different check rules according to different situations

Other Form Controls

Demonstration of validation configuration for form controls which are not shown in the demos above.
China
Please select a country
machines
ABCDEF
longgggggggggggggggggggggggggggggggggg

Click or drag file to this area to upload

Support for a single or bulk upload.

API

Form
PropertyDescriptionTypeDefault
component
Set the Form rendering element. Do not create a DOM node for false
ComponentType | false
form
colon
Configure the default value of colon for Form.Item. Indicates whether the colon after the label is displayed (only effective when prop layout is horizontal)
boolean
true
fields
Control of form fields through state management (such as redux). Not recommended for non-strong demand. View example
-
form
Form control instance created by Form.useForm(). Automatically created when not provided
-
hideRequiredMark
Hide required mark for all form items
boolean
false
initialValues
Set value by Form initialization or reset
object
-
labelAlign
The text align of label of all items
left | right
right
labelCol
Label layout, like <Col> component. Set span offset value like {span: 3, offset: 12} or sm: {span: 3, offset: 12}
-
layout
Form layout
horizontal | vertical | inline
horizontal
name
Form name. Will be the prefix of Field id
string
-
preserve
Keep field value even when field removed
boolean
true
scrollToFirstError
Auto scroll to first failed field when submit
boolean
false
size
Set field component size (antd components only)
small | middle | large
-
validateMessages
Validation prompt template, description see below
-
validateTrigger
Config field validate trigger
string | string[]
onChange
wrapperCol
The layout for input controls, same as labelCol
-
onFinish
Trigger after submitting the form and verifying data successfully
function(values)
-
onFinishFailed
Trigger after submitting the form and verifying data failed
function({ values, errorFields, outOfDate })
-
onFieldsChange
Trigger when field updated
function(changedFields, allFields)
-
onValuesChange
Trigger when value updated
function(changedValues, allValues)
-

Form.Item

PropertyDescriptionTypeDefault
colon
Used with label, whether to display : after label text.
boolean
true
dependencies
Set the dependency field. See below
-
extra
The extra prompt message. It is similar to help. Usage example: to display error message and prompt message at the same time
string | ReactNode
-
getValueFromEvent
Specify how to get value from event or other onChange arguments
(..args: any[]) => any
-
getValueProps
Additional props with sub component
(value: any) => any
-
hasFeedback
Used with validateStatus, this option specifies the validation status icon. Recommended to be used only with Input
boolean
false
help
The prompt message. If not provided, the prompt message will be generated by the validation rule.
string | ReactNode
-
htmlFor
Set sub label htmlFor
string
-
initialValue
Config sub default value. Form initialValues get higher priority when conflict
string
-
noStyle
No style for true, used as a pure field control
boolean
false
label
Label text
string | ReactNode
-
labelAlign
The text align of label
left | right
right
labelCol
The 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>. You can set labelCol on Form. If both exists, use Item first',
-
name
Field name, support array
-
normalize
Normalize value from component value before passing to Form instance
(value, prevValue, prevValues) => any
-
preserve
Keep field value even when field removed
boolean
true
required
Display required style. It will be generated by the validation rule
boolean
false
rules
Rules for field validation. Click here to see an example
-
shouldUpdate
Custom field update logic. See below
boolean | (prevValue, curValue) => boolean
false
trigger
When to collect the value of children node
string
onChange
validateFirst
Whether stop validate on first rule of error for this field
boolean
false
validateStatus
The validation status. If not provided, it will be generated by validation rule. options: success warning error validating
string
-
validateTrigger
When to validate the value of children node
string | string[]
onChange
valuePropName
Props of children node, for example, the prop of Switch is 'checked'. This prop is an encapsulation of getValueProps, which will be invalid after customizing getValueProps
string
value
wrapperCol
The layout for input controls, same as labelCol. You can set wrapperCol on Form. If both exists, use Item first
-
hidden
Whether to hide Form.Item (still collect and validate value)
boolean
false

Form.List

PropertyDescriptionTypeDefault
name
Field name, support array
-
children
Render function
(fields: Field[], operation: { add, remove, move }) => React.ReactNode
-

Form.Provider

PropertyDescriptionTypeDefault
onFormChange
Triggered when a sub form field updates
Function(formName: string, info: { changedFields, forms })
-
onFormFinish
Triggered when a sub form submits
Function(formName: string, info: { values, forms })
-
FormInstance
PropertyDescriptionTypeDefault
getFieldInstance
Get field instance
(name: NamePath) => any
getFieldValue
Get the value by the field name
(name: NamePath) => any
getFieldsValue
Get values by a set of field names. Return according to the corresponding structure
(nameList?: NamePath[], filterFunc?: (meta: { touched: boolean, validating: boolean }) => boolean) => any
getFieldError
Get the error messages by the field name
(name: NamePath) => string[]
getFieldsError
Get the error messages by the fields name. Return as an array
(nameList?: NamePath[]) => FieldError[]
isFieldTouched
Check if a field has been operated
(name: NamePath) => boolean
isFieldsTouched
Check if fields have been operated. Check if all fields is touched when allTouched is true
(nameList?: NamePath[], allTouched?: boolean) => boolean
isFieldValidating
Check fields if is in validating
(name: NamePath) => boolean
resetFields
Reset fields to initialValues
(fields?: NamePath[]) => void
scrollToField
Scroll to field position
(name: NamePath, options: [ScrollOptions]) => void
setFields
Set fields status
(fields: FieldData[]) => void
setFieldsValue
Set fields value
(values) => void
submit
Submit the form. It`s same as click submit button
() => void
validateFields
Validate fields
(nameList?: NamePath[]) => Promise
FieldData
PropertyDescriptionTypeDefault
touched
Whether is operated
boolean
validating
Whether is in validating
boolean
errors
Error messages
string[]
name
Field name path
value
Field value
any
Rule
PropertyDescriptionTypeDefault
enum
Match enum value
any[]
len
Length of string, number, array
number
max
type required: max length of string, number, array
number
message
Error message. Will auto generate by template if not provided
string
min
type required: min length of string, number, array
number
pattern
Regex pattern
RegExp
required
Required field
boolean
transform
Transform value to the rule before validation
(value) => any
type
Normally string |number |boolean |url | email. More type to ref here
string
validator
Customize validation rule. Accept Promise as return. See example
(rule, value) => Promise
whitespace
Failed if only has whitespace
boolean
validateTrigger
Set validate trigger event. Must be the sub set of validateTrigger in Form.Item
string | string[]