index.en-US.md 12.4 KB
Newer Older
G
Gray Choi 已提交
1 2
---
category: Components
D
ddcat1115 已提交
3
type: Data Entry
G
Gray Choi 已提交
4
cols: 1
B
Benjy Cui 已提交
5
title: Form
G
Gray Choi 已提交
6 7
---

A
afc163 已提交
8
Form is used to collect, validate, and submit the user input, usually contains various form items including checkbox, radio, input, select, and etc.
G
Gray Choi 已提交
9 10 11

## Form

W
Wei Zhu 已提交
12
You can align the controls of a `form` using the `layout` prop:
G
Gray Choi 已提交
13

A
afc163 已提交
14
- `horizontal`:to horizontally align the `label`s and controls of the fields. (Default)
15 16
- `vertical`:to vertically align the `label`s and controls of the fields.
- `inline`:to render form fields in one line.
G
Gray Choi 已提交
17

M
Marius Ileana 已提交
18
## Form fields
G
Gray Choi 已提交
19

A
Andrew Murray 已提交
20
A form consists of one or more form fields whose type includes input, textarea, checkbox, radio, select, tag, and more.
M
Marius Ileana 已提交
21
A form field is defined using `<Form.Item />`.
G
Gray Choi 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34

```jsx
<Form.Item {...props}>
  {children}
</Form.Item>
```

## API

### Form

**more example [rc-form](http://react-component.github.io/form/)**

W
Wei Zhu 已提交
35 36
| Property | Description | Type | Default Value |
| -------- | ----------- | ---- | ------------- |
A
afc163 已提交
37
| form | Decorated by `Form.create()` will be automatically set `this.props.form` property | object | n/a |
W
Wei Zhu 已提交
38
| hideRequiredMark | Hide required mark of all form items | Boolean | false |
A
afc163 已提交
39
| layout | Define form layout | 'horizontal'\|'vertical'\|'inline' | 'horizontal' |
M
Marius Ileana 已提交
40
| onSubmit | Defines a function will be called if form data validation is successful. | Function(e:Event) |  |
G
Gray Choi 已提交
41 42 43 44 45 46 47 48 49 50 51

### Form.create(options)

How to use:

```jsx
class CustomizedForm extends React.Component {}

CustomizedForm = Form.create({})(CustomizedForm);
```

M
Marius Ileana 已提交
52
The following `options` are available:
G
Gray Choi 已提交
53

W
Wei Zhu 已提交
54 55
| Property | Description | Type |
| -------- | ----------- | ---- |
A
afc163 已提交
56
| mapPropsToFields | Convert props to field value(e.g. reading the values from Redux store). And you must mark returned fields with [`Form.createFormField`](#Form.createFormField) | (props) => ({ \[fieldName\]: FormField { value } }) |
Z
zombiej 已提交
57
| name | Set the id prefix of fields under form | - |
W
Wei Zhu 已提交
58
| validateMessages | Default validate message. And its format is similar with [newMessages](https://github.com/yiminghe/async-validator/blob/master/src/messages.js)'s returned value | Object { [nested.path]&#x3A; String } |
W
Wei Zhu 已提交
59
| onFieldsChange | Specify a function that will be called when the value a `Form.Item` gets changed. Usage example: saving the field's value to Redux store. | Function(props, fields) |
60
| onValuesChange | A handler while value of any field is changed | (props, changedValues, allValues) => void |
61

M
muzea 已提交
62
If you want to get `ref` after `Form.create`, you can use `wrappedComponentRef` provided by `rc-form`[details can be viewed here](https://github.com/react-component/form#note-use-wrappedcomponentref-instead-of-withref-after-rc-form140).
63 64 65 66 67 68 69 70 71

```jsx
class CustomizedForm extends React.Component { ... }

// use wrappedComponentRef
const EnhancedForm =  Form.create()(CustomizedForm);
<EnhancedForm wrappedComponentRef={(form) => this.form = form} />
this.form // => The instance of CustomizedForm
```
G
Gray Choi 已提交
72

M
Marius Ileana 已提交
73
If the form has been decorated by `Form.create` then it has `this.props.form` property. `this.props.form` provides some APIs as follows:
G
Gray Choi 已提交
74

75 76
> Note: Before using `getFieldsValue` `getFieldValue` `setFieldsValue` and so on, please make sure that corresponding field had been registered with `getFieldDecorator`.

W
Wei Zhu 已提交
77 78 79 80 81 82
| Method | Description | Type |
| ------ | ----------- | ---- |
| getFieldDecorator | Two-way binding for form, please read below for details. |  |
| getFieldError | Get the error of a field. | Function(name) |
| getFieldsError | Get the specified fields' error. If you don't specify a parameter, you will get all fields' error. | Function(\[names: string\[]]) |
| getFieldsValue | Get the specified fields' values. If you don't specify a parameter, you will get all fields' values. | Function(\[fieldNames: string\[]]) |
M
Marius Ileana 已提交
83
| getFieldValue | Get the value of a field. | Function(fieldName: string) |
W
Wei Zhu 已提交
84 85 86 87
| isFieldsTouched | Check whether any of fields is touched by `getFieldDecorator`'s `options.trigger` event | (names?: string\[]) => boolean |
| isFieldTouched | Check whether a field is touched by `getFieldDecorator`'s `options.trigger` event | (name: string) => boolean |
| isFieldValidating | Check if the specified field is being validated. | Function(name) |
| resetFields | Reset the specified fields' value(to `initialValue`) and status. If you don't specify a parameter, all the fields will be reset. | Function(\[names: string\[]]) |
H
huishiyi 已提交
88
| setFields | Set value and error state of fields. [Code Sample](https://github.com/react-component/form/blob/3b9959b57ab30b41d8890ff30c79a7e7c383cad3/examples/server-validate.js#L74-L79) | ({<br />&nbsp;&nbsp;\[fieldName\]: {value: any, errors: \[Error\] }<br />}) => void |
A
afc163 已提交
89
| setFieldsValue | Set the value of a field. (Note: please don't use it in `componentWillReceiveProps`, otherwise, it will cause an endless loop, [reason](https://github.com/ant-design/ant-design/issues/2985)) | ({ \[fieldName\]&#x3A; value }) => void |
Z
ztplz 已提交
90
| validateFields | Validate the specified fields and get theirs values and errors. If you don't specify the parameter of fieldNames, you will validate all fields. | (<br />&nbsp;&nbsp;\[fieldNames: string\[]],<br />&nbsp;&nbsp;\[options: object\],<br />&nbsp;&nbsp;callback(errors, values)<br />) => void |
M
Marius Ileana 已提交
91
| validateFieldsAndScroll | This function is similar to `validateFields`, but after validation, if the target field is not in visible area of form, form will be automatically scrolled to the target field area. | same as `validateFields` |
G
Gray Choi 已提交
92

A
afc163 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106
### validateFields/validateFieldsAndScroll

```jsx
const { form: { validateFields } } = this.props;
validateFields((errors, values) => {
  // ...
});
validateFields(['field1', 'field2'], (errors, values) => {
  // ...
});
validateFields(['field1', 'field2'], options, (errors, values) => {
  // ...
});
```
107

108
| Method | Description | Type | Default |
W
Wei Zhu 已提交
109
| ------ | ----------- | ---- | ------- |
110
| options.first | If `true`, every field will stop validation at first failed rule | boolean | false |
W
Wei Zhu 已提交
111
| options.firstFields | Those fields will stop validation at first failed rule | String\[] | \[] |
112 113 114
| options.force | Should validate validated field again when `validateTrigger` is been triggered again | boolean | false |
| options.scroll | Config scroll behavior of `validateFieldsAndScroll`, more: [dom-scroll-into-view's config](https://github.com/yiminghe/dom-scroll-into-view#function-parameter) | Object | {} |

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
#### Callback arguments example of validateFields

- `errors`:

   ```js
   {
     "userName": {
       "errors": [
         {
           "message": "Please input your username!",
           "field": "userName"
         }
       ]
     },
     "password": {
       "errors": [
         {
           "message": "Please input your Password!",
           "field": "password"
         }
       ]
     }
   }
   ```

- `values`:

   ```js
   {
     "userName": "username",
     "password": "password",
   }
   ```

B
Benjy Cui 已提交
149 150 151 152
### Form.createFormField

To mark the returned fields data in `mapPropsToFields`, [demo](#components-form-demo-global-state).

153
### this.props.form.getFieldDecorator(id, options)
G
Gray Choi 已提交
154

B
Benjy Cui 已提交
155
After wrapped by `getFieldDecorator`, `value`(or other property defined by `valuePropName`) `onChange`(or other property defined by `trigger`) props will be added to form controls,the flow of form data will be handled by Form which will cause:
A
afc163 已提交
156

F
Ffloriel 已提交
157
1. You shouldn't use `onChange` to collect data, but you still can listen to `onChange`(and so on) events.
158
2. You cannot set value of form control via `value` `defaultValue` prop, and you should set default value with `initialValue` in `getFieldDecorator` instead.
F
Ffloriel 已提交
159
3. You shouldn't call `setState` manually, please use `this.props.form.setFieldsValue` to change value programmatically.
A
afc163 已提交
160

G
Gray Choi 已提交
161 162
#### Special attention

B
Benjy Cui 已提交
163
1. `getFieldDecorator` can not be used to decorate stateless component.
W
Wei Zhu 已提交
164
2. If you use `react@<15.3.0`, then, you can't use `getFieldDecorator` in stateless component: <https://github.com/facebook/react/pull/6534>
G
Gray Choi 已提交
165

偏右 已提交
166
#### getFieldDecorator(id, options) parameters
G
Gray Choi 已提交
167

W
Wei Zhu 已提交
168 169 170 171
| Property | Description | Type | Default Value |
| -------- | ----------- | ---- | ------------- |
| id | The unique identifier is required. support [nested fields format](https://github.com/react-component/form/pull/48). | string |  |
| options.getValueFromEvent | Specify how to get value from event or other onChange arguments | function(..args) | [reference](https://github.com/react-component/form#option-object) |
172
| options.getValueProps | Get the component props according to field value. | function(value): any | [reference](https://github.com/react-component/form#option-object)
Z
ztplz 已提交
173
| options.initialValue | You can specify initial value, type, optional value of children node. (Note: Because `Form` will test equality with `===` internally, we recommend to use variable as `initialValue`, instead of literal) |  | n/a |
A
afc163 已提交
174
| options.normalize | Normalize value to form component, [a select-all example](https://codepen.io/afc163/pen/JJVXzG?editors=001) | function(value, prevValue, allValues): any | - |
W
Wei Zhu 已提交
175 176 177 178 179
| options.rules | Includes validation rules. Please refer to "Validation Rules" part for details. | object\[] | n/a |
| options.trigger | When to collect the value of children node | string | 'onChange' |
| options.validateFirst | Whether stop validate on first rule of error for this field. | boolean | false |
| options.validateTrigger | When to validate the value of children node. | string\|string\[] | 'onChange' |
| options.valuePropName | Props of children node, for example, the prop of Switch is 'checked'. | string | 'value' |
A
afc163 已提交
180 181

More option at [rc-form option](https://github.com/react-component/form#option-object)
G
Gray Choi 已提交
182 183 184

### Form.Item

A
afc163 已提交
185
Note: if Form.Item has multiple children that had been decorated by `getFieldDecorator`, `help` and `required` and `validateStatus` can't be generated automatically.
W
Wei Zhu 已提交
186 187 188 189

| Property | Description | Type | Default Value |
| -------- | ----------- | ---- | ------------- |
| colon | Used with `label`, whether to display `:` after label text. | boolean | true |
W
Wei Zhu 已提交
190
| 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 |  |
W
Wei Zhu 已提交
191 192 193 194
| 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 |  |
| label | Label text | string\|ReactNode |  |
| 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>` | [object](https://ant.design/components/grid/#Col) |  |
A
afc163 已提交
195
| required | Whether provided or not, it will be generated by the validation rule. | boolean | false |
A
afc163 已提交
196
| validateStatus | The validation status. If not provided, it will be generated by validation rule. options: 'success' 'warning' 'error' 'validating' | string |  |
W
Wei Zhu 已提交
197
| wrapperCol | The layout for input controls, same as `labelCol` | [object](https://ant.design/components/grid/#Col) |  |
198 199 200

### Validation Rules

W
Wei Zhu 已提交
201 202 203 204 205
| Property | Description | Type | Default Value |
| -------- | ----------- | ---- | ------------- |
| enum | validate a value from a list of possible values | string | - |
| len | validate an exact length of a field | number | - |
| max | validate a max length of a field | number | - |
206
| message | validation error message | string\|ReactNode | - |
W
Wei Zhu 已提交
207 208 209 210 211 212 213
| min | validate a min length of a field | number | - |
| pattern | validate from a regular expression | RegExp | - |
| required | indicates whether field is required | boolean | `false` |
| transform | transform a value before validation | function(value) => transformedValue:any | - |
| type | built-in validation type, [available options](https://github.com/yiminghe/async-validator#type) | string | 'string' |
| validator | custom validate function (Note: [callback must be called](https://github.com/ant-design/ant-design/issues/5155)) | function(rule, value, callback) | - |
| whitespace | treat required fields that only contain whitespace as errors | boolean | `false` |
214 215 216

See more advanced usage at [async-validator](https://github.com/yiminghe/async-validator).

L
LeezQ 已提交
217 218 219 220
## Using in TypeScript

```jsx
import { Form } from 'antd';
221
import { FormComponentProps } from 'antd/lib/form';
L
LeezQ 已提交
222 223 224 225 226 227 228

interface UserFormProps extends FormComponentProps {
  age: number;
  name: string;
}

class UserForm extends React.Component<UserFormProps, any> {
A
afc163 已提交
229
  // ...
L
LeezQ 已提交
230
}
W
Wei Zhu 已提交
231
```
A
afc163 已提交
232 233 234 235 236 237 238 239 240 241

<style>
.code-box-demo .ant-form:not(.ant-form-inline):not(.ant-form-vertical) {
  max-width: 600px;
}
.markdown.api-container table td:last-child {
  white-space: nowrap;
  word-wrap: break-word;
}
</style>