ant-design/components/form/index.en-US.md

256 lines
14 KiB
Markdown
Raw Normal View History

2016-07-31 09:53:51 +08:00
---
category: Components
type: Data Entry
2016-07-31 09:53:51 +08:00
cols: 1
2016-09-21 11:28:38 +08:00
title: Form
2016-07-31 09:53:51 +08:00
---
2016-10-07 14:33:08 +08:00
Form is used to collect, validate, and submit the user input, usually contains various form items including checkbox, radio, input, select, and etc.
2016-07-31 09:53:51 +08:00
## When to use
- When you need to create a instance or collect information.
- When you need to validate fields in certain rules.
## Form Component
2016-07-31 09:53:51 +08:00
2017-11-30 09:53:32 +08:00
You can align the controls of a `form` using the `layout` prop
2016-07-31 09:53:51 +08:00
2017-01-05 16:57:41 +08:00
- `horizontal`to horizontally align the `label`s and controls of the fields. (Default)
- `vertical`to vertically align the `label`s and controls of the fields.
- `inline`to render form fields in one line.
2016-07-31 09:53:51 +08:00
## Form Item Component
2016-07-31 09:53:51 +08:00
2016-09-01 18:12:12 +08:00
A form consists of one or more form fields whose type includes input, textarea, checkbox, radio, select, tag, and more.
A form field is defined using `<Form.Item />`.
2016-07-31 09:53:51 +08:00
```jsx
<Form.Item {...props}>
{children}
</Form.Item>
```
## API
### Form
**more example [rc-form](http://react-component.github.io/form/)**。
2017-10-25 10:25:44 +08:00
| Property | Description | Type | Default Value |
| -------- | ----------- | ---- | ------------- |
2018-09-12 21:43:01 +08:00
| form | Decorated by `Form.create()` will be automatically set `this.props.form` property | object | n/a |
2017-10-25 10:25:44 +08:00
| hideRequiredMark | Hide required mark of all form items | Boolean | false |
2019-03-07 15:14:27 +08:00
| labelAlign | Label text align | 'left' \| 'right' | 'right' |
| 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) | |
2018-09-12 21:43:01 +08:00
| layout | Define form layout | 'horizontal'\|'vertical'\|'inline' | 'horizontal' |
| onSubmit | Defines a function will be called if form data validation is successful. | Function(e:Event) | |
| 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) | |
2019-03-08 11:25:37 +08:00
| colon | change default props colon value of Form.Item | boolean | true |
2016-07-31 09:53:51 +08:00
### Form.create(options)
How to use
```jsx
class CustomizedForm extends React.Component {}
CustomizedForm = Form.create({})(CustomizedForm);
```
The following `options` are available:
2016-07-31 09:53:51 +08:00
2017-10-25 10:25:44 +08:00
| Property | Description | Type |
| -------- | ----------- | ---- |
2019-04-05 00:39:03 +08:00
| 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). Please note that the form fields will become controlled components. Properties like errors will not be automatically mapped and need to be manually passed in. | (props) => ({ \[fieldName\]: FormField { value } }) |
2018-12-17 10:02:08 +08:00
| name | Set the id prefix of fields under form | - |
| 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 } |
| onFieldsChange | Specify a function that will be called when the fields (including errors) of a `Form.Item` gets changed. Usage example: saving the field's value to Redux store. | Function(props, changedFields, allFields) |
| onValuesChange | A handler while value of any field is changed | (props, changedValues, allValues) => void |
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).
```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
```
2016-07-31 09:53:51 +08:00
If the form has been decorated by `Form.create` then it has `this.props.form` property. `this.props.form` provides some APIs as follows:
2016-07-31 09:53:51 +08:00
> Note: Before using `getFieldsValue` `getFieldValue` `setFieldsValue` and so on, please make sure that corresponding field had been registered with `getFieldDecorator`.
2017-10-25 10:25:44 +08:00
| 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\[]]) |
| getFieldValue | Get the value of a field. | Function(fieldName: string) |
2017-10-25 10:25:44 +08:00
| 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\[]]) |
| 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 |
2018-09-12 22:16:53 +08:00
| 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 |
2018-11-14 17:09:35 +08:00
| 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 |
| 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` |
2016-07-31 09:53:51 +08:00
2018-09-12 22:16:53 +08:00
### validateFields/validateFieldsAndScroll
```jsx
const { form: { validateFields } } = this.props;
validateFields((errors, values) => {
// ...
});
validateFields(['field1', 'field2'], (errors, values) => {
// ...
});
validateFields(['field1', 'field2'], options, (errors, values) => {
// ...
});
```
| Method | Description | Type | Default |
2017-10-25 10:25:44 +08:00
| ------ | ----------- | ---- | ------- |
| options.first | If `true`, every field will stop validation at first failed rule | boolean | false |
2017-10-25 10:25:44 +08:00
| options.firstFields | Those fields will stop validation at first failed rule | String\[] | \[] |
| 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 | {} |
#### 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",
}
```
2017-11-17 21:19:10 +08:00
### Form.createFormField
To mark the returned fields data in `mapPropsToFields`, [demo](#components-form-demo-global-state).
### this.props.form.getFieldDecorator(id, options)
2016-07-31 09:53:51 +08:00
2019-02-06 20:51:46 +08:00
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:
2016-10-18 21:12:52 +08:00
1. You shouldn't use `onChange` to collect data, but you still can listen to `onChange`(and so on) events.
2. You cannot set value of form control via `value` `defaultValue` prop, and you should set default value with `initialValue` in `getFieldDecorator` instead.
3. You shouldn't call `setState` manually, please use `this.props.form.setFieldsValue` to change value programmatically.
2016-10-18 21:12:52 +08:00
2016-07-31 09:53:51 +08:00
#### Special attention
2019-03-05 20:51:32 +08:00
If you use `react@<15.3.0`, then, you can't use `getFieldDecorator` in stateless component: <https://github.com/facebook/react/pull/6534>
2016-07-31 09:53:51 +08:00
#### getFieldDecorator(id, options) parameters
2016-07-31 09:53:51 +08:00
2017-10-25 10:25:44 +08:00
| 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) |
2018-08-29 11:20:33 +08:00
| options.getValueProps | Get the component props according to field value. | function(value): any | [reference](https://github.com/react-component/form#option-object)
2018-11-14 17:09:35 +08:00
| 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 |
2017-07-16 15:05:48 +08:00
| options.normalize | Normalize value to form component, [a select-all example](https://codepen.io/afc163/pen/JJVXzG?editors=001) | function(value, prevValue, allValues): any | - |
2018-12-21 23:58:31 +08:00
| options.preserve | Keep the field even if field removed | boolean | - |
2017-10-25 10:25:44 +08:00
| 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' |
2017-07-16 15:05:48 +08:00
More option at [rc-form option](https://github.com/react-component/form#option-object)。
2016-07-31 09:53:51 +08:00
### Form.Item
2018-09-14 11:31:53 +08:00
Note: if Form.Item has multiple children that had been decorated by `getFieldDecorator`, `help` and `required` and `validateStatus` can't be generated automatically.
2017-10-25 10:25:44 +08:00
meger feature to master (#16421) * use ul in list * update snapshot * update comment * feat: TreeSelect support `showSearch` in multiple mode (#15933) * update rc-tree-select * typo * update desc & snapshot * update desc & snapshot * check default showSearch * feat: table customizing variable (#15971) * feat: added table selected row color variable * fix: @table-selected-row-color default is inherit * feat: Upload support customize previewFile (#15984) * support preview file * use promise * dealy load * use canvas of render * use domHook of test * update demo * add snapshot * update types * update testcase * feat: form customizing variables (#15954) * fix: added styling form input background-color * feat: added '@form-warning-input-bg' variable * feat: added '@form-error-input-bg' variable * use li wrap with comment * feat: Support append theme less file with less-variable (#16118) * add override * add override support * update doc * feat: dropdown support set right icon * docs: update doc of dropdown component * style: format dropdown-button.md * test: update updateSnapshot * style: format dropdown-button.md * test: update updateSnapshot * test: update updateSnapshot * style: change style of dropdown-button demo * fix: fix document table order * feat: Support SkeletonAvatarProps.size accept number (#16078) (#16128) * chore:update style of demo * feat: Notification functions accept top, bottom and getContainer as arguments * drawer: add afterVisibleChange * rm onVisibleChange * update * feat: 🇭🇷 hr_HR locale (#16258) * Added Croatian locale * fixed lint error * :white_check_mark: Add test cases for hr_HR * :memo: update i18n documentation * feat: add `htmlFor` in Form.Item (#16278) * add htmlFor in Form.Item * update doc * feat: Button support `link` type (#16289) close #15892 * feat: Add Timeline.Item.position (#16148) (#16193) * fix: Timeline.pendingDot interface documentation there is a small problem (#16177) * feat: Add Timeline.Item.position (#16148) * doc: add version infomation for Timeline.Item.position * refactor: Update Tree & TreeSelect deps (#16330) * use CSSMotion * update snapshot * feat: Collapse support `expandIconPosition` (#16365) * update doc * support expandIconPosition * update snapshot * feat: Breadcrumb support DropDown (#16315) * breadcrumbs support drop down menu * update doc * add require less * fix test * fix md doc * less code * fix style warning * update snap * add children render test * feat: TreeNode support checkable * feat: add optional to support top and left slick dots (#16186) (#16225) * add optional to support top and left slick dots * update carousel snapshot * Update doc, add placement demo * update carousel placement demo snapshots * rename dots placement to position * update vertical as deprecated * rename dotsPosition to dotPosition * refine code * add warning testcase for vertical * remove unused warning * update expression * Additional test case for dotPosition * refactor: Upgrade `rc-tree-select` to support pure React motion (#16402) * upgrade `rc-tree-select` * update snapshot * 3.17.0 changelog * fix warning * fix review warning
2019-05-06 12:04:39 +08:00
| Property | Description | Type | Default Value | Version |
| -------- | ----------- | ---- | ------------- | ------- |
| colon | Used with `label`, whether to display `:` after label text. | boolean | true | |
| 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 | | |
| 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 | | 3.17.0 |
| 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>`. 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) | | |
| required | Whether provided or not, it will be generated by the validation rule. | boolean | false | |
| validateStatus | The validation status. If not provided, it will be generated by validation rule. options: 'success' 'warning' 'error' 'validating' | string | | |
| 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) | | |
### Validation Rules
2017-10-25 10:25:44 +08:00
| 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 | - |
| message | validation error message | string\|ReactNode | - |
2017-10-25 10:25:44 +08:00
| 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` |
See more advanced usage at [async-validator](https://github.com/yiminghe/async-validator).
## Using in TypeScript
```jsx
import { Form } from 'antd';
import { FormComponentProps } from 'antd/lib/form';
interface UserFormProps extends FormComponentProps {
age: number;
name: string;
}
class UserForm extends React.Component<UserFormProps, any> {
2018-09-12 22:16:53 +08:00
// ...
}
const App = Form.create<UserFormProps>({
// ...
})(UserForm);
2017-10-25 10:25:44 +08:00
```
2018-09-12 22:16:53 +08:00
<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>