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

formApi.md

292 lines9.1 KB

1---
2id: formApi
3title: Form API
4---
5​
6### Creating a new FormApi Instance
7​
8​
9​
10Normally, 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.
11​
12```tsx
13const formApi: FormApi<TData> = new FormApi(formOptions: FormOptions<TData>)
14```
15​
16### `FormOptions<TData, ValidatorType>`
17​
18An object representing the options for a form.
19​
20- ```tsx
21 defaultValues?: TData
22 ```
23 - Set initial values for yonu form.
24- ```tsx
25 defaultState?: Partial<FormState<TData>>
26 ```
27 - The default state for the form.
28​
29- ```tsx
30 asyncDebounceMs?: number
31 ```
32 - Optional time in milliseconds if you want to introduce a delay before firing off an async action.
33​
34- ```tsx
35 onMount?: (values: TData, formApi: FormApi<TData>) => ValidationError
36 ```
37 - Optional function that fires as soon as the component mounts.
38- ```tsx
39 onMountAsync?: ( values: TData, formApi: FormApi<TData>) => ValidationError | Promise<ValidationError>
40 ```
41 - Optional async function that fires when the component mounts
42- ```tsx
43 onMountAsyncDebounceMs?: number
44 ```
45 - 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.
46​
47- ```tsx
48 onChange?: (values: TData, formApi: FormApi<TData>) => ValidationError
49 ```
50 - Optional function that checks the validity of your data whenever a value changes
51​
52- ```tsx
53 onChangeAsync?: (values: TData, formApi: FormApi<TData>) => ValidationError | Promise<ValidationError>
54 ```
55 - Optional onChange asynchronous counterpart to onChange. Useful for more complex validation logic that might involve server requests.
56​
57- ```tsx
58 onChangeAsyncDebounceMs?: number
59 ```
60 - 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.
61​
62- ```tsx
63 onBlur?: (values: TData, formApi: FormApi<TData>) => ValidationError
64 ```
65 - Optional function that validates the form data when a field loses focus, returns a `ValidationError`
66​
67- ```tsx
68 onBlurAsync?: (values: TData,formApi: FormApi<TData>) => ValidationError | Promise<ValidationError>
69 ```
70 - Optional onBlur asynchronous validation method for when a field loses focus return a `ValidationError` or a promise of `Promise<ValidationError>`
71​
72- ```tsx
73 onBlurAsyncDebounceMs?: number
74 ```
75 - 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.
76​
77- ```tsx
78 onSubmit?: (values: TData, formApi: FormApi<TData>) => any | Promise<any>
79 ```
80 - 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>`
81​
82- ```tsx
83 onSubmitInvalid?: (values: TData, formApi: FormApi<TData>) => void
84 ```
85 - Specify an action for scenarios where the user tries to submit an invalid form.
86​
87​
88### `FormApi<TFormData, ValidatorType>`
89​
90A class representing the Form API. It handles the logic and interactions with the form state.
91​
92#### Properties
93​
94- ```tsx
95 options: FormOptions<TFormData> = {}
96 ```
97 - The options for the form.
98- ```tsx
99 store: Store<FormState<TFormData>>
100 ```
101 - An internal mechanism that keeps track of the form's state.
102- ```tsx
103 state: FormState<TFormData>
104 ```
105 - The current state of the form.
106- ```tsx
107 fieldInfo: Record<DeepKeys<TFormData>, FieldInfo<TFormData>> ={} as any
108 ```
109 - A record of field information for each field in the form.
110- ```tsx
111 fieldName?: string
112 ```
113 - An optional string representing the name of the field.
114- ```tsx
115 validationMeta: ValidationMeta
116 ```
117 - The validation metadata for the form.
118​
119#### Methods
120​
121- ```tsx
122 constructor(opts?: FormOptions<TFormData>)
123 ```
124 - Constructs a new `FormApi` instance with the given form options.
125- ```tsx
126 update(options: FormOptions<TFormData>)
127 ```
128 - Updates the form options and form state.
129- ```tsx
130 reset()
131 ```
132 - Resets the form state to the default values.
133- ```tsx
134 validateAllFields()
135 ```
136 - Validates all fields in the form.
137​
138- ```tsx
139 handleSubmit()
140 ```
141 - Handles the form submission, performs validation, and calls the appropriate onSubmit or onInvalidSubmit callbacks.
142- ```tsx
143 getFieldValue<TField extends DeepKeys<TFormData>>(field: TField)
144 ```
145 - Gets the value of the specified field.
146- ```tsx
147 getFieldMeta<TField extends DeepKeys<TFormData>>(field: TField)
148 ```
149 - Gets the metadata of the specified field.
150- ```tsx
151 getFieldInfo<TField extends DeepKeys<TFormData>>(field: TField)
152 ```
153 - Gets the field info of the specified field.
154- ```tsx
155 setFieldMeta<TField extends DeepKeys<TFormData>>(field: TField, updater: Updater<FieldMeta>)
156 ```
157 - Updates the metadata of the specified field.
158- ```tsx
159 setFieldValue<TField extends DeepKeys<TFormData>>(field: TField, updater: Updater<DeepValue<TFormData, TField>>, opts?: { touch?: boolean })
160 ```
161 - Sets the value of the specified field and optionally updates the touched state.
162- ```tsx
163 pushFieldValue<TField extends DeepKeys<TFormData>>(field: TField, value: DeepValue<TFormData, TField>, opts?: { touch?: boolean })
164 ```
165 - Pushes a value into an array field.
166- ```tsx
167 insertFieldValue<TField extends DeepKeys<TFormData>>(field: TField, index: number, value: DeepValue<TFormData, TField>, opts?: { touch?: boolean })
168 ```
169 - Inserts a value into an array field at the specified index.
170- ```tsx
171 removeFieldValue<TField extends DeepKeys<TFormData>>(field: TField, index: number, opts?: { touch?: boolean })
172 ```
173 - Removes a value from an array field at the specified index.
174- ```tsx
175 swapFieldValues<TField extends DeepKeys<TFormData>>(field: TField, index1: number, index2: number)
176 ```
177 - Swaps the values at the specified indices within an array field.
178​
179### `FormState<TData>`
180​
181An object representing the current state of the form.
182​
183- ```tsx
184 values: TData
185 ```
186 - The current values of the form fields.
187- ```tsx
188 isFormValidating: boolean
189 ```
190 - A boolean indicating if the form is currently validating.
191- ```tsx
192 formValidationCount: number
193 ```
194 - A counter for tracking the number of validations performed on the form.
195- ```tsx
196 isFormValid: boolean
197 ```
198 - A boolean indicating if the form is valid.
199- ```tsx
200 formError?: ValidationError
201 ```
202 - A possible validation error for the form.
203- ```tsx
204 fieldMeta: Record<DeepKeys<TData>, FieldMeta>
205 ```
206 - A record of field metadata for each field in the form.
207- ```tsx
208 isFieldsValidating: boolean
209 ```
210 - A boolean indicating if any of the form fields are currently validating.
211- ```tsx
212 isFieldsValid: boolean
213 ```
214 - A boolean indicating if all the form fields are valid.
215- ```tsx
216 isSubmitting: boolean
217 ```
218 - A boolean indicating if the form is currently submitting.
219- ```tsx
220 isTouched: boolean
221 ```
222 - A boolean indicating if any of the form fields have been touched.
223- ```tsx
224 isSubmitted: boolean
225 ```
226 - A boolean indicating if the form has been submitted.
227- ```tsx
228 isValidating: boolean
229 ```
230 - A boolean indicating if the form or any of its fields are currently validating.
231- ```tsx
232 isValid: boolean
233 ```
234 - A boolean indicating if the form and all its fields are valid.
235- ```tsx
236 canSubmit: boolean
237 ```
238 - A boolean indicating if the form can be submitted based on its current state.
239- ```tsx
240 submissionAttempts: number
241 ```
242 - A counter for tracking the number of submission attempts.
243​
244### `FieldInfo<TFormData>`
245​
246An object representing the field information for a specific field within the form.
247​
248- ```tsx
249 instances: Record<string, FieldApi<any, TFormData>>
250 ```
251 - A record of field instances with unique identifiers as keys.
252 - Check below for `ValidationMeta`
253​
254​
255​
256### `ValidationMeta`
257​
258An object representing the validation metadata for a field.
259​
260- ```tsx
261 validationCount?: number
262 ```
263 - A counter for tracking the number of validations performed on the field.
264​
265- ```tsx
266 validationAsyncCount?: number
267 ```
268 - A counter for tracking the number of validations performed on the field async.
269- ```tsx
270 validationPromise?: Promise<ValidationError>
271 ```
272 - A promise representing the current validation state of the field.
273- ```tsx
274 validationResolve?: (error: ValidationError) => void
275 ```
276 - A function to resolve the validation promise with a possible validation error.
277- ```tsx
278 validationReject?: (error: unknown) => void
279 ```
280 - A function to reject the validation promise with an error.
281​
282### `ValidationError`
283​
284A type representing a validation error. Possible values are `undefined`, `false`, `null`, or a `string` with an error message.
285​
286### `ValidationErrorMapKeys`
287A type representing the keys used to map to `ValidationError` in `ValidationErrorMap`. It is defined with `on${Capitalize<ValidationCause>}`
288​
289​
290### `ValidationErrorMap`
291​
292A type that represents a map with the keys as `ValidationErrorMapKeys` and the values as `ValidationError`