index.en-US.md 13.2 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 |
yoyo83773's avatar
yoyo83773 已提交
39
| labelAlign | Label text align | 'left' \| 'right' | 'right' |
40
| labelCol | (Added in 3.14.0. Previous version can only set on FormItem.) 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 已提交
41
| layout | Define form layout | 'horizontal'\|'vertical'\|'inline' | 'horizontal' |
M
Marius Ileana 已提交
42
| onSubmit | Defines a function will be called if form data validation is successful. | Function(e:Event) |  |
43
| wrapperCol | (Added in 3.14.0. Previous version can only set on FormItem.) The layout for input controls, same as `labelCol` | [object](https://ant.design/components/grid/#Col) |  |
D
DiamondYuan 已提交
44
| colon | change default props colon value of Form.Item | boolean | true |
G
Gray Choi 已提交
45 46 47 48 49 50 51 52 53 54 55

### Form.create(options)

How to use:

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

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

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

W
Wei Zhu 已提交
58 59
| Property | Description | Type |
| -------- | ----------- | ---- |
A
afc163 已提交
60
| 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 已提交
61
| name | Set the id prefix of fields under form | - |
Z
zombieJ 已提交
62
| 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]: String } |
W
Wei Zhu 已提交
63
| 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) |
64
| onValuesChange | A handler while value of any field is changed | (props, changedValues, allValues) => void |
65

Z
zombieJ 已提交
66
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).
67 68 69 70 71 72 73 74 75

```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 已提交
76

M
Marius Ileana 已提交
77
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 已提交
78

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

W
Wei Zhu 已提交
81 82 83 84 85 86
| 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 已提交
87
| getFieldValue | Get the value of a field. | Function(fieldName: string) |
W
Wei Zhu 已提交
88 89 90 91
| 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 已提交
92
| 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 已提交
93
| 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 已提交
94
| 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 已提交
95
| 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 已提交
96

A
afc163 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110
### validateFields/validateFieldsAndScroll

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

112
| Method | Description | Type | Default |
W
Wei Zhu 已提交
113
| ------ | ----------- | ---- | ------- |
114
| options.first | If `true`, every field will stop validation at first failed rule | boolean | false |
W
Wei Zhu 已提交
115
| options.firstFields | Those fields will stop validation at first failed rule | String\[] | \[] |
116 117 118
| 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 | {} |

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 149 150 151 152
#### 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 已提交
153 154 155 156
### Form.createFormField

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

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

Z
zy410419243 已提交
159
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 已提交
160

F
Ffloriel 已提交
161
1. You shouldn't use `onChange` to collect data, but you still can listen to `onChange`(and so on) events.
162
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 已提交
163
3. You shouldn't call `setState` manually, please use `this.props.form.setFieldsValue` to change value programmatically.
A
afc163 已提交
164

G
Gray Choi 已提交
165 166
#### Special attention

W
wanli 已提交
167
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 已提交
168

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

W
Wei Zhu 已提交
171 172 173 174
| 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) |
175
| options.getValueProps | Get the component props according to field value. | function(value): any | [reference](https://github.com/react-component/form#option-object)
Z
ztplz 已提交
176
| 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 已提交
177
| options.normalize | Normalize value to form component, [a select-all example](https://codepen.io/afc163/pen/JJVXzG?editors=001) | function(value, prevValue, allValues): any | - |
Z
zombiej 已提交
178
| options.preserve | Keep the field even if field removed | boolean | - |
W
Wei Zhu 已提交
179 180 181 182 183
| 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 已提交
184 185

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

### Form.Item

A
afc163 已提交
189
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 已提交
190 191 192 193

| Property | Description | Type | Default Value |
| -------- | ----------- | ---- | ------------- |
| colon | Used with `label`, whether to display `:` after label text. | boolean | true |
W
Wei Zhu 已提交
194
| 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 已提交
195 196 197
| 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 |  |
198
| 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 on Form one time after 3.14.0. Will take FormItem's prop when both set with Form. | [object](https://ant.design/components/grid/#Col) |  |
A
afc163 已提交
199
| required | Whether provided or not, it will be generated by the validation rule. | boolean | false |
A
afc163 已提交
200
| validateStatus | The validation status. If not provided, it will be generated by validation rule. options: 'success' 'warning' 'error' 'validating' | string |  |
201
| wrapperCol | The layout for input controls, same as `labelCol`. You can set on Form one time after 3.14.0. Will take FormItem's prop when both set with Form. | [object](https://ant.design/components/grid/#Col) |  |
202 203 204

### Validation Rules

W
Wei Zhu 已提交
205 206 207 208 209
| 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 | - |
210
| message | validation error message | string\|ReactNode | - |
W
Wei Zhu 已提交
211 212 213 214 215 216 217
| 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` |
218 219 220

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

L
LeezQ 已提交
221 222 223 224
## Using in TypeScript

```jsx
import { Form } from 'antd';
225
import { FormComponentProps } from 'antd/lib/form';
L
LeezQ 已提交
226 227 228 229 230 231 232

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

class UserForm extends React.Component<UserFormProps, any> {
A
afc163 已提交
233
  // ...
L
LeezQ 已提交
234
}
235 236 237 238

const App = Form.create<UserFormProps>({
  // ...
})(UserForm);
W
Wei Zhu 已提交
239
```
A
afc163 已提交
240 241 242 243 244 245 246 247 248 249

<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>