From b23ef654acea3cd2b6437fd4949d62dffdbe487a Mon Sep 17 00:00:00 2001 From: fkworld Date: Fri, 12 Jul 2024 16:32:13 +0800 Subject: [PATCH] fix(core): run all types of async validation on fields during submit --- packages/form-core/src/FieldApi.ts | 2 +- packages/form-core/tests/FormApi.spec.ts | 40 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/packages/form-core/src/FieldApi.ts b/packages/form-core/src/FieldApi.ts index eaf54e228..7a5d4b387 100644 --- a/packages/form-core/src/FieldApi.ts +++ b/packages/form-core/src/FieldApi.ts @@ -878,7 +878,7 @@ export class FieldApi< errorMap: { // eslint-disable-next-line ts/no-unnecessary-condition ...prev?.errorMap, - [getErrorMapKey(cause)]: error, + [getErrorMapKey(validateObj.cause)]: error, }, } }) diff --git a/packages/form-core/tests/FormApi.spec.ts b/packages/form-core/tests/FormApi.spec.ts index 7e6a783fb..4b609f282 100644 --- a/packages/form-core/tests/FormApi.spec.ts +++ b/packages/form-core/tests/FormApi.spec.ts @@ -1337,6 +1337,46 @@ describe('form api', () => { ]) }) + it('should run all types of async validation on fields during submit', async () => { + vi.useFakeTimers() + + const form = new FormApi({ + defaultValues: { + firstName: '', + lastName: '', + }, + }) + + const field = new FieldApi({ + form, + name: 'firstName', + validators: { + onChangeAsync: async ({ value }) => { + await sleep(1000) + return value.length > 0 ? undefined : 'first name is required' + }, + onBlurAsync: async ({ value }) => { + await sleep(1000) + return value.length > 3 + ? undefined + : 'first name must be longer than 3 characters' + }, + }, + }) + + field.mount() + + form.handleSubmit() + expect(form.state.isFieldsValid).toEqual(true) + await vi.runAllTimersAsync() + expect(form.state.isFieldsValid).toEqual(false) + expect(form.state.canSubmit).toEqual(false) + expect(form.state.fieldMeta['firstName'].errorMap).toEqual({ + onChange: 'first name is required', + onBlur: 'first name must be longer than 3 characters', + }) + }) + it('should clear onSubmit error when a valid value is entered', async () => { const form = new FormApi({ defaultValues: {