Flutter docs
Default skin

Form

High-performance form component with data domain management. Includes data entry, validation, and corresponding styles.

When to use

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

Examples

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. You can also use ref to get the form instance in class component: https://codesandbox.io/p/sandbox-ngtjtm

Form Layout

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

Form mix layout

Defining a separate layout on Form.Item can achieve multiple layouts for a single form.

Form disabled

Set component to disabled, only works for library components.

Form variants

Change the variant of all components in the form, options include: outlined filled borderless and underlined.

Required style

Switch required or optional style with requiredMark.

Form size

Set component size, only works for library components.

label can wrap

Turn on labelWrap to wrap label if text is long.

No block rule

rule with warningOnly will not block form submit.

Watch Hooks

useWatch helps watch the field change and only re-render for the value change. API Ref.

Validate Trigger

For the async validation scenario, high frequency of verification will cause backend pressure. You can change the verification timing through validateTrigger, or change the verification frequency through validateDebounce, or set the verification short circuit through validateFirst.

Validate Only

Dynamic adjust submit button's disabled status by validateOnly of validateFields.

Path Prefix

In some scenarios, you may want to set a prefix for some fields consistently. You can achieve this effect with HOC.

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 to nest item.

Drag sorting

Combine dnd-kit with the move operation provided by Form.List to drag and sort dynamic form items. Each field's stable key is used as the drag identifier, and move(from, to) is called on drag end to reorder items while keeping the form values in sync.

Complex Dynamic Form Item

Multiple Form.List nested usage scenarios.

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 shows how to use Form.Item with multiple controls. <Form.Item name="field" /> will only bind the control(Input/Select) which is the only children of it. Imagine this case: you added some text description after the Input, then you have to wrap the Input by an extra <Form.Item name="field">. style property of Form.Item could be useful to modify the nested form item layout, or use <Form.Item noStyle /> to turn it into a pure form-binded component(like getFieldDecorator in 3.x). diff - <Form.Item label="Field" name="field"> - <Input /> - </Form.Item> + <Form.Item label="Field" htmlFor="field"> + <Form.Item name="field" noStyle><Input id="field" /></Form.Item> + {/* The nested item binds the input. */} + <span>description</span> + </Form.Item> When the outer labeled Form.Item has no name, it cannot infer the nested control's ID. If the label describes a single control, set htmlFor on the outer item and the same id on the nested control to preserve label-click focus and screen reader association. This demo shows 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 independent error message, using two <Form.Item name="field" noStyle /> to bind each control, make layout inline by customizing style property. > Note that, in this case, no more name property should be left in Form.Item with label. See the Customized Form Controls demo below for more advanced usage.

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. > - Forward the ref or pass the id property to dom to support the scrollToField method.

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. onFieldsChange returns a flat FieldData[]. When a field uses an array name path, FieldData.name keeps that path instead of converting it into a nested object, making it easier to process each field entry in the external state. **Note:** Saving form data globally is not a good practice. You should avoid this if not necessary.

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.

Inline Login Form

Inline login form is often used in navigation bar.

Login Form

Normal login form which can contain more elements.

Registration

Fill in this form to create a new account for you.

Advanced search

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.

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.

Time-related Controls

The value of time-related components is a dayjs 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.

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.

Dynamic Rules

Perform different check rules according to different situations.

Dependencies

Form.Item can set the associated field through the dependencies property. When the value of the associated field changes, the validation and update will be triggered.

getValueProps + normalize

By combining getValueProps and normalize, it is possible to convert the format of value, such as converting the timestamp into a dayjs object and then passing it to the DatePicker.

Slide to error field

When validation fails or manually scroll to the error field.

Other Form Controls

Demonstration of validation configuration for form controls which are not shown in the demos above.

Custom semantic dom styling

You can customize the semantic dom style of Form by passing objects/functions through classNames and styles.

API

Form, Form.Item, Form.List, and Form.Provider are exported from @ceebee/ui/client.

Form

PropertyDescriptionTypeDefaultVersion
classNamesCustomize class for each semantic structure inside the component. Supports object or function.Record<SemanticDOM, string> | (info: { props })=> Record<SemanticDOM, string>-—
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 componentsbooleanfalse4.21.0
componentSet the Form rendering element. Do not create a DOM node for falseComponentType | falseform—
fieldsControl of form fields through state management (such as redux). Not recommended for non-strong demand. View exampleFieldData\[]-—
formForm control instance created by Form.useForm(). Automatically created when not providedFormInstance-—
feedbackIconsCan be passed custom icons while Form.Item element has hasFeedbackFeedbackIcons-5.9.0
initialValuesSet value by Form initialization or resetobject-—
labelAlignThe text align of label of all itemsleft | rightright—
labelWrapwhether label can be wrapbooleanfalse4.18.0
labelColLabel layout, like <Col> component. Set span offset value like {span: 3, offset: 12} or sm: {span: 3, offset: 12}object-—
layoutForm layouthorizontal | vertical | inlinehorizontal—
nameForm name. Will be the prefix of Field idstring-—
preserveKeep field value even when field removed. You can get the preserve field value by getFieldsValue(true)booleantrue4.4.0
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 | optional | ((label: ReactNode, info: { required: boolean }) => ReactNode)truerenderProps: 5.9.0
scrollToFirstErrorAuto scroll to first failed field when submitboolean | Options | { focus: boolean }falsefocus: 5.24.0
sizeSet field component size (antd components only)small | medium | large-—
stylesCustomize inline style for each semantic structure inside the component. Supports object or function.Record<SemanticDOM, CSSProperties> | (info: { props })=> Record<SemanticDOM, CSSProperties>-—
tooltipConfig tooltip propsTooltipProps & { icon?: ReactNode }-6.3.0
validateMessagesValidation prompt template, description see belowValidateMessages-—
validateTriggerConfig field validate triggerstring | string\[]onChange4.3.0
variantVariant of components inside formoutlined | borderless | filled | underlinedoutlined5.13.0 | underlined: 5.24.0
wrapperColThe layout for input controls, same as labelColobject-—
onFieldsChangeTrigger when field updatedfunction(changedFields, allFields)-—
onFinishTrigger after submitting the form and verifying data successfullyfunction(values)-—
onFinishFailedTrigger after submitting the form and verifying data failedfunction({ values, errorFields, outOfDate })-—
onValuesChangeTrigger when value updatedfunction(changedValues, allValues)-—
clearOnDestroyClear form values when the form is unmountedbooleanfalse5.18.0

validateMessages

PropertyDescriptionTypeDefaultVersion
colonUsed with label, whether to display : after label text.booleantrue—
dependenciesSet the dependency field. See belowNamePath\[]-—
extraThe extra prompt message. It is similar to help. Usage example: to display error message and prompt message at the same timeReactNode-—
getValueFromEventSpecify how to get value from event or other onChange arguments(..args: any\[]) => any-—
getValuePropsAdditional props with sub component (It's not recommended to generate dynamic function prop by getValueProps. Please pass it to child component directly)(value: any) => Record<string, any>-4.2.0
hasFeedbackUsed with validateStatus, this option specifies the validation status icon. Recommended to be used only with Input. Also, It can get feedback icons via icons prop.boolean | { icons: FeedbackIcons }falseicons: 5.9.0
helpThe prompt message. If not provided, the prompt message will be generated by the validation rule.ReactNode-—
hiddenWhether to hide Form.Item (still collect and validate value)booleanfalse4.4.0
htmlForSet sub label htmlForstring-—
initialValueConfig sub default value. Form initialValues get higher priority when conflictstring-4.2.0
labelLabel text. When there is no need for a label but it needs to be aligned with a colon, it can be set to nullReactNode-null: 5.22.0
labelAlignThe text alignment of the 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>. You can set labelCol on Form which will not affect nest Item. If both exists, use Item firstobject-—
messageVariablesThe default validate field info, description see belowRecord&lt;string, string>-4.7.0
nameField name, support arrayNamePath-—
normalizeNormalize value from component value before passing to Form instance. Do not support async(value, prevValue, prevValues) => any-—
noStyleNo style for true, used as a pure field control. Will inherit parent Form.Item validateStatus if self validateStatus not configuredbooleanfalse—
preserveKeep field value even when field removedbooleantrue4.4.0
requiredDisplay required style. When not set, it will be generated by the validation rule. Set it to false to disable the style.boolean-—
rulesRules for field validation. Click here to see an exampleRule\[]-—
shouldUpdateCustom field update logic. See belowboolean | (prevValue, curValue) => booleanfalse—
tooltipConfig tooltip contentReactNode | (TooltipProps & { icon?: ReactNode })-4.7.0
triggerWhen to collect the value of children node. Click here to see an examplestringonChange—
validateDebounceDelay milliseconds to start validationnumber-5.9.0
validateFirstWhether stop validate on first rule of error for this field. Will parallel validate when parallel configuredboolean | parallelfalseparallel: 4.5.0
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\[]onChange—
valuePropNameProps of children node, for example, the prop of Switch or Checkbox is checked. This prop is an encapsulation of getValueProps, which will be invalid after customizing getValuePropsstringvalue—
wrapperColThe layout for input controls, same as labelCol. You can set wrapperCol on Form which will not affect nest Item. If both exists, use Item firstobject-—
layoutForm item layouthorizontal | vertical-5.18.0

messageVariables

PropertyDescriptionTypeDefaultVersion
childrenRender function(fields: Field\[], operation: { add, remove, move }, meta: { errors }) => React.ReactNode-—
initialValueConfig sub default value. Form initialValues get higher priority when conflictany\[]-4.9.0
nameField name, support array. List is also a field, so it will return all the values by getFieldsValue. You can change this logic by configNamePath-—
rulesValidate rules, only support customize validator. Should work with ErrorList{ validator, message }\[]-4.7.0
addadd form item(defaultValue?: any, insertIndex?: number) => voidinsertIndex4.6.0
movemove form item(from: number, to: number) => void-—
removeremove form item(index: number | number\[]) => voidnumber\[]4.5.0
errorsError listReactNode\[]-—
onFormChangeTriggered when a sub form field updatesfunction(formName: string, info: { changedFields, forms })-—
onFormFinishTriggered when a sub form submitsfunction(formName: string, info: { values, forms })-—

FormInstance

PropertyDescriptionTypeDefaultVersion
getFieldErrorGet the error messages by the field name(name: NamePath) => string\[]——
getFieldInstanceGet field instance(name: NamePath) => any4.4.0—
getFieldsErrorGet the error messages by the fields name. Return as an array(nameList?: NamePath\[]) => FieldError\[]——
getFieldsValueGet values by a set of field names. Return according to the corresponding structure. Default return mounted field value, but you can use getFieldsValue(true) to get all valuesGetFieldsValue——
getFieldValueGet the value by the field name(name: NamePath) => any——
isFieldsTouchedCheck if fields have been operated. Check if all fields is touched when allTouched is true(nameList?: NamePath\[], allTouched?: boolean) => boolean——
isFieldTouchedCheck if a field has been operated(name: NamePath) => boolean——
isFieldValidatingCheck field if is in validating(name: NamePath) => boolean——
resetFieldsReset fields to initialValues(fields?: NamePath\[]) => void——
scrollToFieldScroll to field position(name: NamePath, options: ScrollOptions | { focus: boolean }) => voidfocus: 5.24.0—
setFieldsSet fields status(fields: FieldData\[]) => void——
setFieldValueSet fields value(Will directly pass to form store and **reset validation message**. If you do not want to modify passed object, please clone first)(name: NamePath, value: any) => void4.22.0—
setFieldsValueSet fields value(Will directly pass to form store and **reset validation message**. If you do not want to modify passed object, please clone first). Use setFieldValue instead if you want to only config single value in Form.List(values) => void——
submitSubmit the form. It's same as click submit button() => void——
validateFieldsValidate fields. Use recursive to validate all the field in the path(nameList?: NamePath\[], config?: ValidateConfig) => Promise——

FieldData

PropertyDescriptionTypeDefaultVersion
errorsError messagesstring\[]——
warningsWarning messagesstring\[]——
nameField name pathNamePath\[]——
touchedWhether is operatedboolean——
validatingWhether is in validatingboolean——
valueField valueany——

Rule

PropertyDescriptionTypeDefaultVersion
defaultFieldValidate rule for all array elements, valid when type is arrayrule——
enumMatch enum value. You need to set type to enum to enable thisany\[]——
fieldsValidate rule for child elements, valid when type is array or objectRecord&lt;string, rule>——
lenLength of string, number, arraynumber——
maxtype required: max length of string, number, arraynumber——
messageError message. Will auto generate by template if not providedstring | ReactElement——
mintype required: min length of string, number, arraynumber——
patternRegex patternRegExp——
requiredRequired fieldboolean——
transformTransform value to the rule before validation(value) => any——
typeNormally string |number |boolean |url | email | tel. More type to ref herestring——
validateTriggerSet validate trigger event. Must be the sub set of validateTrigger in Form.Itemstring | string\[]——
validatorCustomize validation rule. Accept Promise as return. See example(rule, value) => Promise——
warningOnlyWarning only. Not block form submitboolean4.17.0—
whitespaceFailed if only has whitespace, only work with type: 'string' ruleboolean——

WatchOptions

PropertyDescriptionTypeDefaultVersion
formForm instanceFormInstanceCurrent form in context5.4.0
preserveWhether to watch the field which has no matched Form.Itembooleanfalse5.4.0