β Zero dependencies
β Framework agnostic
β Opt-in subscriptions - only update on the state you need!
β π₯ 4.2k gzipped π₯
π¬ Give Feedback on Final Form π¬
In the interest of making π Final Form the best library it can be, we'd love your thoughts and feedback.
npm install --save final-form
or
yarn add final-form
π Final Form works on subscriptions to perform updates based on the Observer pattern. Both form and field subscribers must specify exactly which parts of the form state they want to receive updates about.
import { createForm } from 'final-form'
// Create Form
const form = createForm({
initialValues,
onSubmit, // required
validate
})
// Subscribe to form state updates
const unsubscribe = form.subscribe(
formState => {
// Update UI
},
{ // FormSubscription: the list of values you want to be updated about
dirty: true,
valid: true,
values: true
}
})
// Subscribe to field state updates
const unregisterField = form.registerField(
'username',
fieldState => {
// Update field UI
const { blur, change, focus, ...rest } = fieldState
// In addition to the values you subscribe to, field state also
// includes functions that your inputs need to update their state.
},
{ // FieldSubscription: the list of values you want to be updated about
active: true,
dirty: true,
touched: true,
valid: true,
value: true
}
)
// Submit
form.submit() // only submits if all validation passes
- Examples
- Official Mutators
- Libraries
- Field Names
- API
- Types
Config
debug?: DebugFunction
destroyOnUnregister?: boolean
keepDirtyOnReinitialize?: boolean
initialValues?: Object
mutators?: { [string]: Mutator }
onSubmit: (values: Object, form: FormApi, callback: ?(errors: ?Object) => void) => ?Object | Promise<?Object> | void
validate?: (values: Object) => Object | Promise<Object>
validateOnBlur?: boolean
DebugFunction: (state: FormState, fieldStates: { [string]: FieldState }) => void
Decorator: (form: FormApi) => Unsubscribe
FieldConfig
FieldState
active?: boolean
blur: () => void
change: (value: any) => void
data?: Object
dirty?: boolean
dirtySinceLastSubmit?: boolean
error?: any
focus: () => void
initial?: any
invalid?: boolean
length?: number
name: string
pristine?: boolean
submitError?: any
submitFailed?: boolean
submitSucceeded?: boolean
touched?: boolean
valid?: boolean
value?: any
visited?: boolean
FieldSubscriber: (state: FieldState) => void
FieldSubscription: { [string]: boolean }
active?: boolean
data?: boolean
dirty?: boolean
dirtySinceLastSubmit?: boolean
error?: boolean
initial?: boolean
invalid?: boolean
length?: boolean
pristine?: boolean
submitError?: boolean
submitFailed?: boolean
submitSucceeded?: boolean
touched?: boolean
valid?: boolean
value?: boolean
visited?: boolean
FormApi
batch: (fn: () => void) => void)
blur: (name: string) => void
change: (name: string, value: ?any) => void
focus: (name: string) => void
getFieldState: (field: string) => ?FieldState
getRegisteredFields: () => string[]
getState: () => FormState
initialize: (values: Object) => void
isValidationPaused: () => boolean
mutators: ?{ [string]: Function }
pauseValidation: () => void
registerField: RegisterField
reset: (initialValues: ?Object) => void
resumeValidation: () => void
submit: () => ?Promise<?Object>
subscribe: (subscriber: FormSubscriber, subscription: FormSubscription) => Unsubscribe
FormState
active?: string
dirty?: boolean
error?: any
errors?: Object
hasSubmitErrors?: boolean
hasValidationErrors?: boolean
initialValues?: Object
invalid?: boolean
pristine?: boolean
submitError?: any
submitErrors?: Object
submitFailed?: boolean
submitSucceeded?: boolean
submitting?: boolean
touched: { [string]: boolean }
valid?: boolean
validating?: boolean
values?: Object
visited: { [string]: boolean }
FormSubscriber: (state: FormState) => void
FormSubscription: { [string]: boolean }
active?: boolean
dirty?: boolean
dirtySinceLastSubmit?: boolean
error?: boolean
errors?: boolean
hasSubmitErrors?: boolean
hasValidationErrors?: boolean
initialValues?: boolean
invalid?: boolean
pristine?: boolean
setConfig: (name: string, value: any) => void
submitError?: boolean
submitErrors?: boolean
submitFailed?: boolean
submitSucceeded?: boolean
submitting?: boolean
touched?: boolean
valid?: boolean
validating?: boolean
values?: boolean
visited?: boolean
InternalFieldState
active: boolean
blur: () => void
change: (value: any) => void
data: Object
focus: () => void
isEqual: (a: any, b: any) => boolean
name: string
touched: boolean
validateFields: ?(string[])
validators: { [number]: (value: ?any, allValues: Object) => ?any | Promise<?any> } }
valid: boolean
visited: boolean
InternalFormState
MutableState
Mutator: (args: any[], state: MutableState, tools: Tools) => any
RegisterField: (name: string, subscriber: FieldSubscriber, subscription: FieldSubscription, config?: FieldConfig) => Unsubscribe
Tools
Unsubscribe : () => void
- Contributors
- Backers
- Sponsors
Demonstrates how π Final Form can be used inside a React component to manage form state. It also shows just how much π React Final Form does for you out of the box.
For more examples using React, see π React Final Form Examples.
Mutators are functions that can be provided to π Final Form that are allowed to mutate any part of the form state. You provide an object of mutators when you call createForm()
, and then they are exposed (bound to the form state) on the form
instance you get back, under form.mutators.whatever()
. A mutator function is given: the arguments it was called with, the form state, and a collection of utility functions, like getIn
and setIn
to read and mutate arbitrarily deep values, as well as changeValue
, which updates a field value in the form state. They can mutate the state however they wish, and then the form and field subscribers that need to be notified will be notified. Read more about Mutators.
Helps managing array structures in form data.
Sets arbitrary data for fields.
Allows control over the touched
flags for fields.
A form state management system for React that uses π Final Form under the hood.
A form state management system for Vue that uses π Final Form under the hood.
Define Form offers alternative typescript bindings for π Final Form. The key difference is that the form data is now a strongly typed object, rather than an any
. This makes the initialValues
config option required.
A "decorator" that will attempt to apply focus to the first field with an error upon an attempted form submission.
A swap-in replacement for π React Final Form's <Field>
component to provide HTML5 Validation.
A collection of useful components for listening to fields in a π React Final Form.
Field names are strings that allow dot-and-bracket syntax, allowing you to create arbitrarily deeply nested fields. There are four main things you need to understand about how field names are used to read and write the form values in π Final Form.
.
and[
are treated the same.]
is ignored.Number
keys will result in array structures. Why?- Setting
undefined
to a field value deletes any empty object β but not array! β structures. Why?
It is very similar to Lodash's _.set()
, except that empty structures are removed. Let's look at some examples:
Field Name | Initial Structure | Setting Value | Result |
---|---|---|---|
bar |
{} |
'foo' |
{ bar: 'foo' } |
bar.frog |
{} |
'foo' |
{ bar: { frog: 'foo' } } |
bar[0] |
{} |
'foo' |
{ bar: [ 'foo' ] } |
bar.0 |
{} |
'foo' |
{ bar: [ 'foo' ] } |
bar[1] |
{} |
'foo' |
{ bar: [ null, 'foo' ] } |
bar[0].frog |
{} |
'foo' |
{ bar: [ { frog: 'foo' } ] } |
bar |
{ bar: 'foo' } |
undefined |
{ } |
bar.frog |
{ bar: { frog: 'foo' }, other: 42 } |
undefined |
{ other: 42 } |
bar.frog[0] |
{ bar: { frog: [ 'foo' ] } } |
undefined |
{ bar: { frog: [ null ] } } |
Here is a sandbox that you can play around with to get a better understanding of how it works.
The following can be imported from final-form
.
Creates a form instance. It takes a Config
and returns a
FormApi
.
An Γ la carte list of all the possible things you can subscribe to for a field. Useful for subscribing to everything.
An Γ la carte list of all the possible things you can subscribe to for a form. Useful for subscribing to everything.
A special string
key used to return an error for an array of fields.
A special string
key used to return a whole-form error inside error objects
returned from validation or submission.
The current used version of π Final Form.
If true
, the value of a field will be destroyed when that field is unregistered. Defaults to false
. Can be useful when creating dynamic forms where only form values displayed need be submitted.
If true
, only pristine values will be overwritten when initialize(newValues)
is called. This can be useful for allowing a user to continue to edit a record while the record is being saved asynchronously, and the form is reinitialized to the saved values when the save is successful. Defaults to false
.
The initial values of your form. These will also be used to compare against the
current values to calculate pristine
and dirty
.
Optional named mutation functions.
onSubmit: (values: Object, form: FormApi, callback: ?(errors: ?Object) => void) => ?Object | Promise<?Object> | void
Function to call when the form is submitted. There are three possible ways to
write an onSubmit
function:
- Synchronously: returns
undefined
on success, or anObject
of submission errors on failure - Asynchronously with a callback: returns
undefined
, callscallback()
with no arguments on success, or with anObject
of submission errors on failure. - Asynchronously with a
Promise
: returns aPromise<?Object>
that resolves with no value on success or resolves with anObject
of submission errors on failure. The reason it resolves with errors is to leave rejection for when there is a server or communications error.
Submission errors must be in the same shape as the values of the form. You may
return a generic error for the whole form (e.g. 'Login Failed'
) using the
special FORM_ERROR
string key.
A whole-record validation function that takes all the values of the form and
returns any validation errors. There are three possible ways to write a
validate
function:
- Synchronously: returns
{}
orundefined
when the values are valid, or anObject
of validation errors when the values are invalid. - Asynchronously with a
Promise
: returns aPromise<?Object>
that resolves with no value on success or resolves with anObject
of validation errors on failure. The reason it resolves with errors is to leave rejection for when there is a server or communications error.
Validation errors must be in the same shape as the values of the form. You may
return a generic error for the whole form using the special FORM_ERROR
string
key.
If true
, validation will happen on blur. If false
, validation will happen on
change. Defaults to false
.
An optional callback for debugging that receives the form state and the states of
all the fields. It's called on every state change. A typical thing to pass in
might be console.log
.
A function that decorates a
form by subscribing to it and making changes as the form state changes, and
returns an Unsubscribe
function to detach itself from
the form. e.g.
π Final Form Calculate.
A function to determine if two values are equal. Defaults to ===
.
A callback that will return a field-level validation function to validate a single field value. The validation function should return an error if the value is not valid, or undefined
if the value is valid.
An array of field names to validate when this field changes. If undefined
,
every field will be validated when this one changes; if []
, only this
field will have its field-level validation function called when it changes; if
other field names are specified, those fields and this one will be validated
when this field changes.
FieldState
is an object containing:
Whether or not the field currently has focus.
A function to blur the field (mark it as inactive).
A function to change the value of the field.
A place for arbitrary values to be placed by mutators.
true
when the value of the field is not equal to the initial value (using the isEqual
comparator provided at field registration), false
if the values are equal.
true
when the value of the field is not equal to the value last submitted (using the isEqual
comparator provided at field registration), false
if the values are equal.
The current validation error for this field.
A function to focus the field (mark it as active).
The initial value of the field. undefined
if it was never initialized.
true
if the field has a validation error or a submission error. false
otherwise.
The length of the array if the value is an array. undefined
otherwise.
The name of the field.
true
if the current value is ===
to the initial value, false
if the values
are !===
.
The submission error for this field.
true
if a form submission has been tried and failed. false
otherwise.
true
if the form has been successfully submitted. false
otherwise.
true
if this field has ever gained and lost focus. false
otherwise. Useful
for knowing when to display error messages.
true
if this field has no validation or submission errors. false
otherwise.
The value of the field.
true
if this field has ever gained focus.
FieldSubscription
is an object containing the following:
When true
the FieldSubscriber
will be notified of changes to the active
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the data
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the dirty
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the dirtySinceLastSubmit
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the error
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the initial
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the invalid
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the length
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the pristine
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the
submitError
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the
submitFailed
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the
submitSucceeded
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the touched
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the valid
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the value
value in FieldState
.
When true
the FieldSubscriber
will be notified of changes to the visited
value in FieldState
.
Allows batch updates by silencing notifications while the fn
is running.
Example:
form.batch(() => {
form.change('firstName', 'Erik') // listeners not notified
form.change('lastName', 'Rasmussen') // listeners not notified
}) // NOW all listeners notified
Blurs (marks inactive) the given field.
Changes the value of the given field.
Focuses (marks active) the given field.
Returns the state of a specific field as it was last reported to its listeners, or undefined
if the field has not been registered.
Returns a list of all the currently registered fields.
A way to request the current state of the form without subscribing.
Initializes the form to the values provided. All the values will be set to these
values, and dirty
and pristine
will be calculated by performing a
shallow-equals between the current values and the values last initialized with.
The form will be pristine
after this call.
Returns true
if validation is currently paused, false
otherwise.
The state-bound versions of the mutators provided to Config
.
If called, validation will be paused until resumeValidation()
is called.
Registers a new field and subscribes to changes to it. The subscriber
will
only be called when the values specified in subscription
change. More than
one subscriber can subscribe to the same field.
This is also where you may provide an optional field-level validation function
that should return undefined
if the value is valid, or an error. It can
optionally return a Promise
that resolves (not rejects) to undefined
or an
error.
Resets the values back to the initial values the form was initialized with. Or empties all the values if the form was not initialized. If you provide initialValues
they will be used as the new initial values.
Note that if you are calling reset()
and not specify new initial values, you must call it with no arguments. Be careful to avoid things like promise.catch(reset)
or onChange={form.reset}
in React, as they will get arguments passed to them and reinitialize your form.
Resumes validation paused by pauseValidation()
. If validation was blocked while it was paused, validation will be run.
Submits the form if there are currently no validation errors. It may return
undefined
or a Promise
depending on the nature of the onSubmit
configuration value given to the form when it was created.
Subscribes to changes to the form. The subscriber
will only be called when
values specified in subscription
change. A form can have many subscribers.
The name of the currently active field. undefined
if none are active.
true
if the form values are different from the values it was initialized with.
false
otherwise. Comparison is done with shallow-equals.
The whole-form error returned by a validation function under the FORM_ERROR
key.
An object containing all the current validation errors. The shape will match the shape of the form's values.
true
when the form currently has submit errors. Useful for distinguishing why invalid
is true
.
true
when the form currently has validation errors. Useful for distinguishing why invalid
is true
. For example, if your form is invalid
because of a submit error, you might also want to disable the submit button if user's changes to fix the submit errors causes the form to have sync validation errors.
The values the form was initialized with. undefined
if the form was never
initialized.
true
if any of the fields or the form has a validation or submission error.
false
otherwise. Note that a form can be invalid even if the errors do not
belong to any currently registered fields.
true
if the form values are the same as the initial values. false
otherwise.
Comparison is done with shallow-equals.
The whole-form submission error returned by onSubmit
under the FORM_ERROR
key.
An object containing all the current submission errors. The shape will match the shape of the form's values.
true
if the form was submitted, but the submission failed with submission
errors. false
otherwise.
true
if the form was successfully submitted. false
otherwise.
true
if the form is currently being submitted asynchronously. false
otherwise.
An object full of booleans, with a boolean value for each field name denoting whether that field is touched
or not. Note that this is a flat object, so if your field name is addresses.shipping.street
, the touched
value for that field will be available under touched['addresses.shipping.street']
.
true
if neither the form nor any of its fields has a validation or submission
error. false
otherwise. Note that a form can be invalid even if the errors do
not belong to any currently registered fields.
true
if the form is currently being validated asynchronously. false
otherwise.
The current values of the form.
An object full of booleans, with a boolean value for each field name denoting whether that field is visited
or not. Note that this is a flat object, so if your field name is addresses.shipping.street
, the visited
value for that field will be available under visited['addresses.shipping.street']
.
FormSubscription
is an object containing the following:
When true
the FormSubscriber
will be notified of changes to the active
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the dirty
value in FormState
. This value is the opposite to the pristine
valueΒ (dirty = !pristine
).
When true
the FormSubscriber
will be notified of changes to the dirtySinceLastSubmit
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the error
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the errors
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the
hasSubmitErrors
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the
hasValidationErrors
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the
initialValues
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the invalid
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the pristine
value in FormState
.
Allows mutating the values on the original Config
.
When true
the FormSubscriber
will be notified of changes to the
submitError
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the
submitErrors
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the
submitFailed
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the
submitSucceeded
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the submitting
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the touched
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the valid
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the validating
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the values
value in FormState
.
When true
the FormSubscriber
will be notified of changes to the visited
value in FormState
.
Very similar to the published FieldState
.
Whether or not the field currently has focus.
A function to blur the field (mark it as inactive).
A function to change the value of the field.
A place for arbitrary values to be placed by mutators.
A function to focus the field (mark it as active).
A function to determine if two values are equal. Used to calculate
pristine
/dirty
.
The name of the field.
true
if this field has ever gained and lost focus. false
otherwise. Useful
for knowing when to display error messages.
Fields to validate when this field value changes.
Field-level validators for each field that is registered.
true
if this field has no validation or submission errors. false
otherwise.
true
if this field has ever gained focus.
Very similar to the published FormState
, with a few minor
differences.
The name of the currently active field. undefined
if none are active.
true
if the form values have changed since the last time the form was submitted, false
otherwise.
The whole-form error returned by a validation function under the FORM_ERROR
key.
An object containing all the current validation errors. The shape will match the shape of the form's values.
The values the form was initialized with. undefined
if the form was never
initialized.
The values last submitted. Used to calculate dirtySinceLastSubmit
.
true
if the form values are the same as the initial values. false
otherwise.
Comparison is done with shallow-equals.
The whole-form submission error returned by onSubmit
under the FORM_ERROR
key.
An object containing all the current submission errors. The shape will match the shape of the form's values.
true
if the form was submitted, but the submission failed with submission
errors. false
otherwise.
true
if the form was successfully submitted. false
otherwise.
true
if the form is currently being submitted asynchronously. false
otherwise.
true
if neither the form nor any of its fields has a validation or submission
error. false
otherwise. Note that a form can be invalid even if the errors do
not belong to any currently registered fields.
The number of asynchronous validators currently running.
The current values of the form.
MutableState
is an object containing the following:
The InternalFormState
.
An object of InternalFieldState
s.
A mutator function that takes some arguments, the internal form
MutableState
, and some Tools
and optionally
modifies the form state.
RegisterField: (name: string, subscriber: FieldSubscriber, subscription: FieldSubscription, config?: FieldConfig) => Unsubscribe
Takes a name, and a
FieldSubscriber
,
FieldSubscription
, and a
FieldConfig
and registers a field subscription. Learn more about how Field Names.
An object containing:
A utility function to modify a single field value in form state. mutate()
takes the old value and returns the new value.
A utility function to get any arbitrarily deep value from an object using
dot-and-bracket syntax (e.g. some.deep.values[3].whatever
).
A utility function to set any arbitrarily deep value inside an object using
dot-and-bracket syntax (e.g. some.deep.values[3].whatever
). Note: it does
not mutate the object, but returns a new object.
A utility function to compare the keys of two objects. Returns true
if the
objects have the same keys and the values are ===
, false
otherwise.
Unsubscribes a listener.
This project exists thanks to all the people who contribute. [Contribute].
Thank you to all our backers! π [Become a backer]
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]