Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

formApi.md

296 lines8.7 KB

1---
2id: formApi
3title: Form API
4---
5​
6### Creating a new FormApi Instance
7​
8Normally, you will not need to create a new `FormApi` instance directly. Instead, you will use a framework hook/function like `useForm` or `createForm` to create a new instance for you that utilizes your frameworks reactivity model. However, if you need to create a new instance manually, you can do so by calling the `new FormApi` constructor.
9​
10```tsx
11const formApi: FormApi<TData> = new FormApi(formOptions: FormOptions<TData>)
12```
13​
14### `FormOptions<TFormData, TFormValidator>`
15​
16An object representing the options for a form.
17​
18- ```tsx
19 asyncDebounceMs?: number
20 ```
21 - Optional time in milliseconds if you want to introduce a delay before firing off an async action.
22​
23- ```tsx
24 asyncAlways?: boolean
25 ```
26 - If true, always run async validation, even when sync validation has produced an error. Defaults to `undefined`.
27​
28- ```tsx
29 defaultValues?: TData
30 ```
31 - Set initial values for your form.
33- ```tsx
34 defaultState?: Partial<FormState<TData>>
35 ```
36 - The default state for the form.
37​
38- ```tsx
39 onSubmit?: (values: TData, formApi: FormApi<TData>) => any | Promise<any>
40 ```
41 - A function to be called when the form is submitted, what should happen once the user submits a valid form returns `any` or a promise `Promise<any>`
42​
43- ```tsx
44 onSubmitInvalid?: (values: TData, formApi: FormApi<TData>) => void
45 ```
46 - Specify an action for scenarios where the user tries to submit an invalid form.
47​
48- ```tsx
49 validatorAdapter?: TFormValidator
50 ```
51 - A validator adapter to support usage of extra validation types (IE: Zod, Yup, or Valibot usage)
52​
53- ```tsx
54 validators?: FormValidators<TFormData, TFormValidator>
55 ```
56 - A list of validators to pass to the form
57​
58### `FormValidators<TFormData, TFormValidator>`
59​
60- ```tsx
61 onMount?: (values: TData, formApi: FormApi<TData>) => ValidationError
62 ```
63 - Optional function that fires as soon as the component mounts.
65- ```tsx
66 onChange?: (values: TData, formApi: FormApi<TData>) => ValidationError
67 ```
68 - Optional function that checks the validity of your data whenever a value changes
69​
70- ```tsx
71 onChangeAsync?: (values: TData, formApi: FormApi<TData>) => ValidationError | Promise<ValidationError>
72 ```
73 - Optional onChange asynchronous counterpart to onChange. Useful for more complex validation logic that might involve server requests.
74​
75- ```tsx
76 onChangeAsyncDebounceMs?: number
77 ```
78 - The default time in milliseconds that if set to a number larger than 0, will debounce the async validation event by this length of time in milliseconds.
79​
80- ```tsx
81 onBlur?: (values: TData, formApi: FormApi<TData>) => ValidationError
82 ```
83 - Optional function that validates the form data when a field loses focus, returns a `ValidationError`
84​
85- ```tsx
86 onBlurAsync?: (values: TData,formApi: FormApi<TData>) => ValidationError | Promise<ValidationError>
87 ```
88 - Optional onBlur asynchronous validation method for when a field loses focus return a `ValidationError` or a promise of `Promise<ValidationError>`
89​
90- ```tsx
91 onBlurAsyncDebounceMs?: number
92 ```
93 - The default time in milliseconds that if set to a number larger than 0, will debounce the async validation event by this length of time in milliseconds.
94​
95### `FormApi<TFormData, TFormValidator>`
96​
97A class representing the Form API. It handles the logic and interactions with the form state.
98​
99#### Properties
100​
101- ```tsx
102 options: FormOptions<TFormData> = {}
103 ```
104 - The options for the form.
106- ```tsx
107 store: Store<FormState<TFormData>>
108 ```
109 - A [TanStack Store instance](https://tanstack.com/store/latest/docs/reference/Store) that keeps track of the form's state.
111- ```tsx
112 state: FormState<TFormData>
113 ```
114 - The current state of the form.
116- ```tsx
117 fieldInfo: Record<DeepKeys<TFormData>, FieldInfo<TFormData, TFormValidator>> =
118 {} as any
119 ```
120 - A record of field information for each field in the form.
121​
122#### Methods
123​
124- ```tsx
125 constructor(opts?: FormOptions<TFormData, TFormValidator>)
126 ```
127 - Constructs a new `FormApi` instance with the given form options.
128- ```tsx
129 update(options: FormOptions<TFormData, TFormValidator>)
130 ```
131 - Updates the form options and form state.
132- ```tsx
133 reset()
134 ```
135 - Resets the form state to the default values.
136- ```tsx
137 validateAllFields(cause: ValidationCause): Promise<ValidationError[]>
138 ```
139 - Validates all fields in the form using the correct handlers for a given validation type.
140​
141- ```tsx
142 handleSubmit()
143 ```
144 - Handles the form submission, performs validation, and calls the appropriate `onSubmit` or `onInvalidSubmit` callbacks.
145- ```tsx
146 getFieldValue<TField extends DeepKeys<TFormData>>(field: TField)
147 ```
148 - Gets the value of the specified field.
149- ```tsx
150 getFieldMeta<TField extends DeepKeys<TFormData>>(field: TField)
151 ```
152 - Gets the metadata of the specified field.
153- ```tsx
154 getFieldInfo<TField extends DeepKeys<TFormData>>(field: TField)
155 ```
156 - Gets the field info of the specified field.
157- ```tsx
158 setFieldMeta<TField extends DeepKeys<TFormData>>(field: TField, updater: Updater<FieldMeta>)
159 ```
160 - Updates the metadata of the specified field.
161- ```tsx
162 setFieldValue<TField extends DeepKeys<TFormData>>(field: TField, updater: Updater<DeepValue<TFormData, TField>>, opts?: { touch?: boolean })
163 ```
164 - Sets the value of the specified field and optionally updates the touched state.
165- ```tsx
166 pushFieldValue<TField extends DeepKeys<TFormData>>(field: TField, value: DeepValue<TFormData, TField>, opts?: { touch?: boolean })
167 ```
168 - Pushes a value into an array field.
169- ```tsx
170 insertFieldValue<TField extends DeepKeys<TFormData>>(field: TField, index: number, value: DeepValue<TFormData, TField>, opts?: { touch?: boolean })
171 ```
172 - Inserts a value into an array field at the specified index.
173- ```tsx
174 removeFieldValue<TField extends DeepKeys<TFormData>>(field: TField, index: number, opts?: { touch?: boolean })
175 ```
176 - Removes a value from an array field at the specified index.
177- ```tsx
178 swapFieldValues<TField extends DeepKeys<TFormData>>(field: TField, index1: number, index2: number)
179 ```
180 - Swaps the values at the specified indices within an array field.
181​
182### `FormState<TData>`
183​
184An object representing the current state of the form.
185​
186- ```tsx
187 values: TData
188 ```
189 - The current values of the form fields.
190​
191- ```tsx
192 errors: ValidationError[]
193 ```
194 - The error array for the form itself.
195​
196- ```tsx
197 errorMap: ValidationErrorMap
198 ```
199 - The error map for the form itself.
201- ```tsx
202 isFormValidating: boolean
203 ```
204 - A boolean indicating if the form is currently validating.
206- ```tsx
207 isFormValid: boolean
208 ```
209 - A boolean indicating if the form is valid.
211- ```tsx
212 fieldMeta: Record<DeepKeys<TData>, FieldMeta>
213 ```
214 - A record of field metadata for each field in the form.
216- ```tsx
217 isFieldsValidating: boolean
218 ```
219 - A boolean indicating if any of the form fields are currently validating.
221- ```tsx
222 isFieldsValid: boolean
223 ```
224 - A boolean indicating if all the form fields are valid.
226- ```tsx
227 isSubmitting: boolean
228 ```
229 - A boolean indicating if the form is currently submitting.
231- ```tsx
232 isTouched: boolean
233 ```
234 - A boolean indicating if any of the form fields have been touched.
236- ```tsx
237 isSubmitted: boolean
238 ```
239 - A boolean indicating if the form has been submitted.
241- ```tsx
242 isValidating: boolean
243 ```
244 - A boolean indicating if the form or any of its fields are currently validating.
246- ```tsx
247 isValid: boolean
248 ```
249 - A boolean indicating if the form and all its fields are valid.
251- ```tsx
252 canSubmit: boolean
253 ```
254 - A boolean indicating if the form can be submitted based on its current state.
256- ```tsx
257 submissionAttempts: number
258 ```
259 - A counter for tracking the number of submission attempts.
260​
261- ```tsx
262 validationMetaMap: Record<ValidationErrorMapKeys, ValidationMeta | undefined>
263 ```
264 - An internal mechanism used for keeping track of validation logic in a form.
265​
266### `FieldInfo<TFormData>`
267​
268An object representing the field information for a specific field within the form.
269​
270- ```tsx
271 instances: Record<
272 string,
273 FieldApi<
274 TFormData,
275 any,
276 Validator<unknown, unknown> | undefined,
277 TFormValidator
278 >
279 >
280 ```
281 - A record of field instances with unique identifiers as keys.
282​
283- ```tsx
284 validationMetaMap: Record<ValidationErrorMapKeys, ValidationMeta | undefined>
285 ```
286 - A record of field validation internal handling.
287 - Check below for `ValidationMeta`
288​
289### `ValidationMeta`
290​
291An object representing the validation metadata for a field. Not intended for public usage.
292​
293- ```tsx
294 lastAbortController: AbortController
295 ```
296 - An abort controller stored in memory to cancel previous async validation attempts.