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

FieldApi.ts

992 lines26.3 KB

1import { Store } from '@tanstack/store'
2import { getAsyncValidatorArray, getBy, getSyncValidatorArray } from './utils'
3import type {
4 UpdateMetaOptions,
5 ValidationCause,
6 ValidationError,
7 ValidationErrorMap,
8 Validator,
9} from './types'
10import type { FieldInfo, FormApi } from './FormApi'
11import type { AsyncValidator, SyncValidator, Updater } from './utils'
12import type { DeepKeys, DeepValue, NoInfer } from './util-types'
13​
14/**
15 * @private
16 */
17export type FieldValidateFn<
18 TParentData,
19 TName extends DeepKeys<TParentData>,
20 TFieldValidator extends
21 | Validator<DeepValue<TParentData, TName>, unknown>
22 | undefined = undefined,
23 TFormValidator extends
24 | Validator<TParentData, unknown>
25 | undefined = undefined,
26 TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,
27> = (props: {
28 value: TData
29 fieldApi: FieldApi<TParentData, TName, TFieldValidator, TFormValidator, TData>
30}) => ValidationError
31​
32/**
33 * @private
34 */
35export type FieldValidateOrFn<
36 TParentData,
37 TName extends DeepKeys<TParentData>,
38 TFieldValidator extends
39 | Validator<DeepValue<TParentData, TName>, unknown>
40 | undefined = undefined,
41 TFormValidator extends
42 | Validator<TParentData, unknown>
43 | undefined = undefined,
44 TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,
45> = TFieldValidator extends Validator<TData, infer TFN>
46 ?
47 | TFN
48 | FieldValidateFn<
49 TParentData,
50 TName,
51 TFieldValidator,
52 TFormValidator,
53 TData
54 >
55 : TFormValidator extends Validator<TParentData, infer FFN>
56 ?
57 | FFN
58 | FieldValidateFn<
59 TParentData,
60 TName,
61 TFieldValidator,
62 TFormValidator,
63 TData
64 >
65 : FieldValidateFn<
66 TParentData,
67 TName,
68 TFieldValidator,
69 TFormValidator,
70 TData
71 >
72​
73/**
74 * @private
75 */
76export type FieldValidateAsyncFn<
77 TParentData,
78 TName extends DeepKeys<TParentData>,
79 TFieldValidator extends
80 | Validator<DeepValue<TParentData, TName>, unknown>
81 | undefined = undefined,
82 TFormValidator extends
83 | Validator<TParentData, unknown>
84 | undefined = undefined,
85 TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,
86> = (options: {
87 value: TData
88 fieldApi: FieldApi<TParentData, TName, TFieldValidator, TFormValidator, TData>
89 signal: AbortSignal
90}) => ValidationError | Promise<ValidationError>
91​
92/**
93 * @private
94 */
95export type FieldAsyncValidateOrFn<
96 TParentData,
97 TName extends DeepKeys<TParentData>,
98 TFieldValidator extends
99 | Validator<DeepValue<TParentData, TName>, unknown>
100 | undefined = undefined,
101 TFormValidator extends
102 | Validator<TParentData, unknown>
103 | undefined = undefined,
104 TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,
105> = TFieldValidator extends Validator<TData, infer TFN>
106 ?
107 | TFN
108 | FieldValidateAsyncFn<
109 TParentData,
110 TName,
111 TFieldValidator,
112 TFormValidator,
113 TData
114 >
115 : TFormValidator extends Validator<TParentData, infer FFN>
116 ?
117 | FFN
118 | FieldValidateAsyncFn<
119 TParentData,
120 TName,
121 TFieldValidator,
122 TFormValidator,
123 TData
124 >
125 : FieldValidateAsyncFn<
126 TParentData,
127 TName,
128 TFieldValidator,
129 TFormValidator,
130 TData
131 >
132​
133export interface FieldValidators<
134 TParentData,
135 TName extends DeepKeys<TParentData>,
136 TFieldValidator extends
137 | Validator<DeepValue<TParentData, TName>, unknown>
138 | undefined = undefined,
139 TFormValidator extends
140 | Validator<TParentData, unknown>
141 | undefined = undefined,
142 TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,
143> {
144 /**
145 * An optional function that takes a param of `formApi` which is a generic type of `TData` and `TParentData`
146 */
147 onMount?: FieldValidateOrFn<
148 TParentData,
149 TName,
150 TFieldValidator,
151 TFormValidator,
152 TData
153 >
154 /**
155 * An optional property that takes a `ValidateFn` which is a generic of `TData` and `TParentData`.
156 * If `validatorAdapter` is passed, this may also accept a property from the respective adapter
157 *
158 * @example `z.string().min(1)` if `zodAdapter` is passed
159 */
160 onChange?: FieldValidateOrFn<
161 TParentData,
162 TName,
163 TFieldValidator,
164 TFormValidator,
165 TData
166 >
167 /**
168 * An optional property similar to `onChange` but async validation. If `validatorAdapter`
169 * is passed, this may also accept a property from the respective adapter
170 *
171 * @example `z.string().refine(async (val) => val.length > 3, { message: 'Testing 123' })` if `zodAdapter` is passed
172 */
173 onChangeAsync?: FieldAsyncValidateOrFn<
174 TParentData,
175 TName,
176 TFieldValidator,
177 TFormValidator,
178 TData
179 >
180 /**
181 * An optional number to represent how long the `onChangeAsync` should wait before running
182 *
183 * If set to a number larger than 0, will debounce the async validation event by this length of time in milliseconds
184 */
185 onChangeAsyncDebounceMs?: number
186 /**
187 * An optional list of field names that should trigger this field's `onChange` and `onChangeAsync` events when its value changes
188 */
189 onChangeListenTo?: DeepKeys<TParentData>[]
190 /**
191 * An optional function, that when run when subscribing to blur event of input.
192 * If `validatorAdapter` is passed, this may also accept a property from the respective adapter
193 *
194 * @example `z.string().min(1)` if `zodAdapter` is passed
195 */
196 onBlur?: FieldValidateOrFn<
197 TParentData,
198 TName,
199 TFieldValidator,
200 TFormValidator,
201 TData
202 >
203 /**
204 * An optional property similar to `onBlur` but async validation. If `validatorAdapter`
205 * is passed, this may also accept a property from the respective adapter
206 *
207 * @example `z.string().refine(async (val) => val.length > 3, { message: 'Testing 123' })` if `zodAdapter` is passed
208 */
209 onBlurAsync?: FieldAsyncValidateOrFn<
210 TParentData,
211 TName,
212 TFieldValidator,
213 TFormValidator,
214 TData
215 >
216​
217 /**
218 * An optional number to represent how long the `onBlurAsync` should wait before running
219 *
220 * If set to a number larger than 0, will debounce the async validation event by this length of time in milliseconds
221 */
222 onBlurAsyncDebounceMs?: number
223 /**
224 * An optional list of field names that should trigger this field's `onBlur` and `onBlurAsync` events when its value changes
225 */
226 onBlurListenTo?: DeepKeys<TParentData>[]
227 /**
228 * An optional function, that when run when subscribing to submit event of input.
229 * If `validatorAdapter` is passed, this may also accept a property from the respective adapter
230 *
231 * @example `z.string().min(1)` if `zodAdapter` is passed
232 */
233 onSubmit?: FieldValidateOrFn<
234 TParentData,
235 TName,
236 TFieldValidator,
237 TFormValidator,
238 TData
239 >
240 /**
241 * An optional property similar to `onSubmit` but async validation. If `validatorAdapter`
242 * is passed, this may also accept a property from the respective adapter
243 *
244 * @example `z.string().refine(async (val) => val.length > 3, { message: 'Testing 123' })` if `zodAdapter` is passed
245 */
246 onSubmitAsync?: FieldAsyncValidateOrFn<
247 TParentData,
248 TName,
249 TFieldValidator,
250 TFormValidator,
251 TData
252 >
254​
255/**
256 * An object type representing the options for a field in a form.
257 */
258export interface FieldOptions<
259 TParentData,
260 TName extends DeepKeys<TParentData>,
261 TFieldValidator extends
262 | Validator<DeepValue<TParentData, TName>, unknown>
263 | undefined = undefined,
264 TFormValidator extends
265 | Validator<TParentData, unknown>
266 | undefined = undefined,
267 TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,
268> {
269 /**
270 * The field name. The type will be `DeepKeys<TParentData>` to ensure your name is a deep key of the parent dataset.
271 */
272 name: TName
273 /**
274 * An optional default value for the field.
275 */
276 defaultValue?: NoInfer<TData>
277 /**
278 * The default time to debounce async validation if there is not a more specific debounce time passed.
279 */
280 asyncDebounceMs?: number
281 /**
282 * If `true`, always run async validation, even if there are errors emitted during synchronous validation.
283 */
284 asyncAlways?: boolean
285 /**
286 * A validator provided by an extension, like `yupValidator` from `@tanstack/yup-form-adapter`
287 */
288 validatorAdapter?: TFieldValidator
289 /**
290 * A list of validators to pass to the field
291 */
292 validators?: FieldValidators<
293 TParentData,
294 TName,
295 TFieldValidator,
296 TFormValidator,
297 TData
298 >
299 /**
300 * An optional object with default metadata for the field.
301 */
302 defaultMeta?: Partial<FieldMeta>
304​
305/**
306 * An object type representing the required options for the FieldApi class.
307 */
308export interface FieldApiOptions<
309 TParentData,
310 TName extends DeepKeys<TParentData>,
311 TFieldValidator extends
312 | Validator<DeepValue<TParentData, TName>, unknown>
313 | undefined = undefined,
314 TFormValidator extends
315 | Validator<TParentData, unknown>
316 | undefined = undefined,
317 TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,
318> extends FieldOptions<
319 TParentData,
320 TName,
321 TFieldValidator,
322 TFormValidator,
323 TData
324 > {
325 form: FormApi<TParentData, TFormValidator>
327​
328/**
329 * An object type representing the metadata of a field in a form.
330 */
331export type FieldMeta = {
332 /**
333 * A flag indicating whether the field has been touched.
334 */
335 isTouched: boolean
336 /**
337 * A flag that is `true` if the field's value has not been modified by the user. Opposite of `isDirty`.
338 */
339 isPristine: boolean
340 /**
341 * A flag that is `true` if the field's value has been modified by the user. Opposite of `isPristine`.
342 */
343 isDirty: boolean
344 /**
345 * An array of errors related to the field value.
346 */
347 errors: ValidationError[]
348 /**
349 * A map of errors related to the field value.
350 */
351 errorMap: ValidationErrorMap
352 /**
353 * A flag indicating whether the field is currently being validated.
354 */
355 isValidating: boolean
357​
358/**
359 * An object type representing the state of a field.
360 */
361export type FieldState<TData> = {
362 /**
363 * The current value of the field.
364 */
365 value: TData
366 /**
367 * The current metadata of the field.
368 */
369 meta: FieldMeta
371​
372/**
373 * A class representing the API for managing a form field.
374 *
375 * Normally, you will not need to create a new `FieldApi` instance directly.
376 * Instead, you will use a framework hook/function like `useField` or `createField`
377 * to create a new instance for you that uses your framework's reactivity model.
378 * However, if you need to create a new instance manually, you can do so by calling
379 * the `new FieldApi` constructor.
380 */
381export class FieldApi<
382 TParentData,
383 TName extends DeepKeys<TParentData>,
384 TFieldValidator extends
385 | Validator<DeepValue<TParentData, TName>, unknown>
386 | undefined = undefined,
387 TFormValidator extends
388 | Validator<TParentData, unknown>
389 | undefined = undefined,
390 TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,
391> {
392 /**
393 * A reference to the form API instance.
394 */
395 form: FieldApiOptions<
396 TParentData,
397 TName,
398 TFieldValidator,
399 TFormValidator,
400 TData
401 >['form']
402 /**
403 * The field name.
404 */
405 name!: DeepKeys<TParentData>
406 /**
407 * The field options.
408 */
409 options: FieldApiOptions<
410 TParentData,
411 TName,
412 TFieldValidator,
413 TFormValidator,
414 TData
415 > = {} as any
416 /**
417 * The field state store.
418 */
419 store!: Store<FieldState<TData>>
420 /**
421 * The current field state.
422 */
423 state!: FieldState<TData>
424 /**
425 * @private
426 */
427 prevState!: FieldState<TData>
428​
429 /**
430 * Initializes a new `FieldApi` instance.
431 */
432 constructor(
433 opts: FieldApiOptions<
434 TParentData,
435 TName,
436 TFieldValidator,
437 TFormValidator,
438 TData
439 >,
440 ) {
441 this.form = opts.form as never
442 this.name = opts.name as never
443​
444 if (opts.defaultValue !== undefined) {
445 this.form.setFieldValue(this.name, opts.defaultValue as never, {
446 dontUpdateMeta: true,
447 })
448 }
449​
450 this.store = new Store<FieldState<TData>>(
451 {
452 value: this.getValue(),
453​
454 meta: this._getMeta() ?? {
455 isValidating: false,
456 isTouched: false,
457 isDirty: false,
458 isPristine: true,
459 errors: [],
460 errorMap: {},
461 ...opts.defaultMeta,
462 },
463 },
464 {
465 onUpdate: () => {
466 const state = this.store.state
467​
468 state.meta.errors = Object.values(state.meta.errorMap).filter(
469 (val: unknown) => val !== undefined,
470 )
471​
472 state.meta.isPristine = !state.meta.isDirty
473​
474 this.prevState = state
475 this.state = state
476 },
477 },
478 )
479​
480 this.state = this.store.state
481 this.prevState = this.state
482 this.options = opts as never
483 }
484​
485 /**
486 * @private
487 */
488 runValidator<
489 TValue extends { value: TData; fieldApi: FieldApi<any, any, any, any> },
490 TType extends 'validate' | 'validateAsync',
491 >(props: {
492 validate: TType extends 'validate'
493 ? FieldValidateOrFn<any, any, any, any>
494 : FieldAsyncValidateOrFn<any, any, any, any>
495 value: TValue
496 type: TType
497 }): ReturnType<ReturnType<Validator<any>>[TType]> {
498 const adapters = [
499 this.form.options.validatorAdapter,
500 this.options.validatorAdapter,
501 ] as const
502 for (const adapter of adapters) {
503 if (adapter && typeof props.validate !== 'function') {
504 return adapter()[props.type](
505 props.value as never,
506 props.validate,
507 ) as never
508 }
509 }
510​
511 return (props.validate as FieldValidateFn<any, any>)(props.value) as never
512 }
513​
514 /**
515 * Mounts the field instance to the form.
516 */
517 mount = () => {
518 const info = this.getInfo()
519 info.instance = this as never
520 const unsubscribe = this.form.store.subscribe(() => {
521 this.store.batch(() => {
522 const nextValue = this.getValue()
523 const nextMeta = this.getMeta()
524​
525 if (nextValue !== this.state.value) {
526 this.store.setState((prev) => ({ ...prev, value: nextValue }))
527 }
528​
529 if (nextMeta !== this.state.meta) {
530 this.store.setState((prev) => ({ ...prev, meta: nextMeta }))
531 }
532 })
533 })
534​
535 this.update(this.options as never)
536 const { onMount } = this.options.validators || {}
537​
538 if (onMount) {
539 const error = this.runValidator({
540 validate: onMount,
541 value: {
542 value: this.state.value,
543 fieldApi: this,
544 },
545 type: 'validate',
546 })
547 if (error) {
548 this.setMeta((prev) => ({
549 ...prev,
550 // eslint-disable-next-line ts/no-unnecessary-condition
551 errorMap: { ...prev?.errorMap, onMount: error },
552 }))
553 }
554 }
555​
556 return () => {
557 unsubscribe()
558 }
559 }
560​
561 /**
562 * Updates the field instance with new options.
563 */
564 update = (
565 opts: FieldApiOptions<
566 TParentData,
567 TName,
568 TFieldValidator,
569 TFormValidator,
570 TData
571 >,
572 ) => {
573 // Default Value
574​
575 if (this.state.value === undefined) {
576 const formDefault = getBy(opts.form.options.defaultValues, opts.name)
577​
578 if (opts.defaultValue !== undefined) {
579 this.setValue(opts.defaultValue as never, {
580 dontUpdateMeta: true,
581 })
582 } else if (formDefault !== undefined) {
583 this.setValue(formDefault as never, {
584 dontUpdateMeta: true,
585 })
586 }
587 }
588​
589 // Default Meta
590 if (this._getMeta() === undefined) {
591 this.setMeta(this.state.meta)
592 }
593​
594 this.options = opts as never
595 }
596​
597 /**
598 * Gets the current field value.
599 * @deprecated Use `field.state.value` instead.
600 */
601 getValue = (): TData => {
602 return this.form.getFieldValue(this.name) as TData
603 }
604​
605 /**
606 * Sets the field value and run the `change` validator.
607 */
608 setValue = (updater: Updater<TData>, options?: UpdateMetaOptions) => {
609 this.form.setFieldValue(this.name, updater as never, options)
610 this.validate('change')
611 }
612​
613 /**
614 * @private
615 */
616 _getMeta = () => this.form.getFieldMeta(this.name)
617​
618 /**
619 * Gets the current field metadata.
620 */
621 getMeta = () =>
622 this._getMeta() ??
623 ({
624 isValidating: false,
625 isTouched: false,
626 isDirty: false,
627 isPristine: true,
628 errors: [],
629 errorMap: {},
630 ...this.options.defaultMeta,
631 } as FieldMeta)
632​
633 /**
634 * Sets the field metadata.
635 */
636 setMeta = (updater: Updater<FieldMeta>) =>
637 this.form.setFieldMeta(this.name, updater)
638​
639 /**
640 * Gets the field information object.
641 */
642 getInfo = () => this.form.getFieldInfo(this.name)
643​
644 /**
645 * Pushes a new value to the field.
646 */
647 pushValue = (
648 value: TData extends any[] ? TData[number] : never,
649 opts?: UpdateMetaOptions,
650 ) => this.form.pushFieldValue(this.name, value as any, opts)
651​
652 /**
653 * Inserts a value at the specified index, shifting the subsequent values to the right.
654 */
655 insertValue = (
656 index: number,
657 value: TData extends any[] ? TData[number] : never,
658 opts?: UpdateMetaOptions,
659 ) => this.form.insertFieldValue(this.name, index, value as any, opts)
660​
661 /**
662 * Replaces a value at the specified index.
663 */
664 replaceValue = (
665 index: number,
666 value: TData extends any[] ? TData[number] : never,
667 opts?: UpdateMetaOptions,
668 ) => this.form.replaceFieldValue(this.name, index, value as any, opts)
669​
670 /**
671 * Removes a value at the specified index.
672 */
673 removeValue = (index: number, opts?: UpdateMetaOptions) =>
674 this.form.removeFieldValue(this.name, index, opts)
675​
676 /**
677 * Swaps the values at the specified indices.
678 */
679 swapValues = (aIndex: number, bIndex: number, opts?: UpdateMetaOptions) =>
680 this.form.swapFieldValues(this.name, aIndex, bIndex, opts)
681​
682 /**
683 * Moves the value at the first specified index to the second specified index.
684 */
685 moveValue = (aIndex: number, bIndex: number, opts?: UpdateMetaOptions) =>
686 this.form.moveFieldValues(this.name, aIndex, bIndex, opts)
687​
688 /**
689 * @private
690 */
691 getLinkedFields = (cause: ValidationCause) => {
692 const fields = Object.values(this.form.fieldInfo) as FieldInfo<
693 any,
694 TFormValidator
695 >[]
696​
697 const linkedFields: FieldApi<any, any, any, any>[] = []
698 for (const field of fields) {
699 if (!field.instance) continue
700 const { onChangeListenTo, onBlurListenTo } =
701 field.instance.options.validators || {}
702 if (
703 cause === 'change' &&
704 onChangeListenTo?.includes(this.name as string)
705 ) {
706 linkedFields.push(field.instance)
707 }
708 if (cause === 'blur' && onBlurListenTo?.includes(this.name as string)) {
709 linkedFields.push(field.instance)
710 }
711 }
712​
713 return linkedFields
714 }
715​
716 /**
717 * @private
718 */
719 validateSync = (cause: ValidationCause) => {
720 const validates = getSyncValidatorArray(cause, this.options)
721​
722 const linkedFields = this.getLinkedFields(cause)
723 const linkedFieldValidates = linkedFields.reduce(
724 (acc, field) => {
725 const fieldValidates = getSyncValidatorArray(cause, field.options)
726 fieldValidates.forEach((validate) => {
727 ;(validate as any).field = field
728 })
729 return acc.concat(fieldValidates as never)
730 },
731 [] as Array<SyncValidator<any> & { field: FieldApi<any, any, any, any> }>,
732 )
733​
734 // Needs type cast as eslint errantly believes this is always falsy
735 let hasErrored = false as boolean
736​
737 this.form.store.batch(() => {
738 const validateFieldFn = (
739 field: FieldApi<any, any, any, any>,
740 validateObj: SyncValidator<any>,
741 ) => {
742 const error = normalizeError(
743 field.runValidator({
744 validate: validateObj.validate,
745 value: { value: field.getValue(), fieldApi: field },
746 type: 'validate',
747 }),
748 )
749 const errorMapKey = getErrorMapKey(validateObj.cause)
750 if (field.state.meta.errorMap[errorMapKey] !== error) {
751 field.setMeta((prev) => ({
752 ...prev,
753 errorMap: {
754 ...prev.errorMap,
755 [getErrorMapKey(validateObj.cause)]: error,
756 },
757 }))
758 }
759 if (error) {
760 hasErrored = true
761 }
762 }
763​
764 for (const validateObj of validates) {
765 if (!validateObj.validate) continue
766 validateFieldFn(this, validateObj)
767 }
768 for (const fieldValitateObj of linkedFieldValidates) {
769 if (!fieldValitateObj.validate) continue
770 validateFieldFn(fieldValitateObj.field, fieldValitateObj)
771 }
772 })
773​
774 /**
775 * when we have an error for onSubmit in the state, we want
776 * to clear the error as soon as the user enters a valid value in the field
777 */
778 const submitErrKey = getErrorMapKey('submit')
779 if (
780 this.state.meta.errorMap[submitErrKey] &&
781 cause !== 'submit' &&
782 !hasErrored
783 ) {
784 this.setMeta((prev) => ({
785 ...prev,
786 errorMap: {
787 ...prev.errorMap,
788 [submitErrKey]: undefined,
789 },
790 }))
791 }
792​
793 return { hasErrored }
794 }
795​
796 /**
797 * @private
798 */
799 validateAsync = async (cause: ValidationCause) => {
800 const validates = getAsyncValidatorArray(cause, this.options)
801​
802 const linkedFields = this.getLinkedFields(cause)
803 const linkedFieldValidates = linkedFields.reduce(
804 (acc, field) => {
805 const fieldValidates = getAsyncValidatorArray(cause, field.options)
806 fieldValidates.forEach((validate) => {
807 ;(validate as any).field = field
808 })
809 return acc.concat(fieldValidates as never)
810 },
811 [] as Array<
812 AsyncValidator<any> & { field: FieldApi<any, any, any, any> }
813 >,
814 )
815​
816 if (!this.state.meta.isValidating) {
817 this.setMeta((prev) => ({ ...prev, isValidating: true }))
818 }
819​
820 for (const linkedField of linkedFields) {
821 linkedField.setMeta((prev) => ({ ...prev, isValidating: true }))
822 }
823​
824 /**
825 * We have to use a for loop and generate our promises this way, otherwise it won't be sync
826 * when there are no validators needed to be run
827 */
828 const validatesPromises: Promise<ValidationError | undefined>[] = []
829 const linkedPromises: Promise<ValidationError | undefined>[] = []
830​
831 const validateFieldAsyncFn = (
832 field: FieldApi<any, any, any, any>,
833 validateObj: AsyncValidator<any>,
834 promises: Promise<ValidationError | undefined>[],
835 ) => {
836 const key = getErrorMapKey(validateObj.cause)
837 const fieldValidatorMeta = field.getInfo().validationMetaMap[key]
838​
839 fieldValidatorMeta?.lastAbortController.abort()
840 const controller = new AbortController()
841​
842 this.getInfo().validationMetaMap[key] = {
843 lastAbortController: controller,
844 }
845​
846 promises.push(
847 new Promise<ValidationError | undefined>(async (resolve) => {
848 let rawError!: ValidationError | undefined
849 try {
850 rawError = await new Promise((rawResolve, rawReject) => {
851 setTimeout(async () => {
852 if (controller.signal.aborted) return rawResolve(undefined)
853 try {
854 rawResolve(
855 await this.runValidator({
856 validate: validateObj.validate,
857 value: {
858 value: field.getValue(),
859 fieldApi: field,
860 signal: controller.signal,
861 },
862 type: 'validateAsync',
863 }),
864 )
865 } catch (e) {
866 rawReject(e)
867 }
868 }, validateObj.debounceMs)
869 })
870 } catch (e: unknown) {
871 rawError = e as ValidationError
872 }
873 if (controller.signal.aborted) return resolve(undefined)
874 const error = normalizeError(rawError)
875 field.setMeta((prev) => {
876 return {
877 ...prev,
878 errorMap: {
879 // eslint-disable-next-line ts/no-unnecessary-condition
880 ...prev?.errorMap,
881 [getErrorMapKey(cause)]: error,
882 },
883 }
884 })
885​
886 resolve(error)
887 }),
888 )
889 }
890​
891 // TODO: Dedupe this logic to reduce bundle size
892 for (const validateObj of validates) {
893 if (!validateObj.validate) continue
894 validateFieldAsyncFn(this, validateObj, validatesPromises)
895 }
896 for (const fieldValitateObj of linkedFieldValidates) {
897 if (!fieldValitateObj.validate) continue
898 validateFieldAsyncFn(
899 fieldValitateObj.field,
900 fieldValitateObj,
901 linkedPromises,
902 )
903 }
904​
905 let results: ValidationError[] = []
906 if (validatesPromises.length || linkedPromises.length) {
907 results = await Promise.all(validatesPromises)
908 await Promise.all(linkedPromises)
909 }
910​
911 this.setMeta((prev) => ({ ...prev, isValidating: false }))
912​
913 for (const linkedField of linkedFields) {
914 linkedField.setMeta((prev) => ({ ...prev, isValidating: false }))
915 }
916​
917 return results.filter(Boolean)
918 }
919​
920 /**
921 * Validates the field value.
922 */
923 validate = (
924 cause: ValidationCause,
925 ): ValidationError[] | Promise<ValidationError[]> => {
926 // If the field is pristine and validatePristine is false, do not validate
927 if (!this.state.meta.isTouched) return []
928​
929 try {
930 this.form.validate(cause)
931 } catch (_) {}
932​
933 // Attempt to sync validate first
934 const { hasErrored } = this.validateSync(cause)
935​
936 if (hasErrored && !this.options.asyncAlways) {
937 this.getInfo().validationMetaMap[
938 getErrorMapKey(cause)
939 ]?.lastAbortController.abort()
940 return this.state.meta.errors
941 }
942 // No error? Attempt async validation
943 return this.validateAsync(cause)
944 }
945​
946 /**
947 * Handles the change event.
948 */
949 handleChange = (updater: Updater<TData>) => {
950 this.setValue(updater)
951 }
952​
953 /**
954 * Handles the blur event.
955 */
956 handleBlur = () => {
957 const prevTouched = this.state.meta.isTouched
958 if (!prevTouched) {
959 this.setMeta((prev) => ({ ...prev, isTouched: true }))
960 this.validate('change')
961 }
962 this.validate('blur')
963 }
965​
966function normalizeError(rawError?: ValidationError) {
967 if (rawError) {
968 if (typeof rawError !== 'string') {
969 return 'Invalid Form Values'
970 }
971​
972 return rawError
973 }
974​
975 return undefined
977​
978function getErrorMapKey(cause: ValidationCause) {
979 switch (cause) {
980 case 'submit':
981 return 'onSubmit'
982 case 'blur':
983 return 'onBlur'
984 case 'mount':
985 return 'onMount'
986 case 'server':
987 return 'onServer'
988 case 'change':
989 default:
990 return 'onChange'
991 }