From cbc11e601dcbbb02aae57687cfc67156b0aee1cd Mon Sep 17 00:00:00 2001 From: betavs <34408516+betavs@users.noreply.github.com> Date: Sat, 7 Jun 2025 10:30:26 +0800 Subject: [PATCH] fix(components): [form] the validate function is executed repeatedly (#19345) --- .../components/form/__tests__/form.test.tsx | 44 +++++++++++++++++++ packages/components/form/src/form.vue | 5 ++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/packages/components/form/__tests__/form.test.tsx b/packages/components/form/__tests__/form.test.tsx index c573725b2f..d5eaf28848 100644 --- a/packages/components/form/__tests__/form.test.tsx +++ b/packages/components/form/__tests__/form.test.tsx @@ -806,6 +806,50 @@ describe('Form', () => { expect(inputWrapper.attributes('tabindex')).toBeUndefined() }) + it('validate abnormal callback', async () => { + const form = reactive({ + age: '20', + }) + + const wrapper = mount({ + setup() { + const rules = ref({ + age: [ + { + required: true, + message: 'Please input age', + trigger: 'change', + }, + ], + }) + return () => ( +
+ + + +
+ ) + }, + }) + + const fn = vi.fn() + + await (wrapper.vm.$refs.formRef as FormInstance).validate(() => { + fn() + throw { + age: [ + { + field: 'age', + fieldValue: '', + message: 'Please input age', + }, + ], + } + }) + + expect(fn).toHaveBeenCalledTimes(1) + }) + describe('FormItem', () => { const onSuccess = vi.fn() const onError = vi.fn() diff --git a/packages/components/form/src/form.vue b/packages/components/form/src/form.vue index eab13c7238..e3ee645a17 100644 --- a/packages/components/form/src/form.vue +++ b/packages/components/form/src/form.vue @@ -125,9 +125,10 @@ const validateField: FormContext['validateField'] = async ( modelProps = [], callback ) => { + let result = false const shouldThrow = !isFunction(callback) try { - const result = await doValidateField(modelProps) + result = await doValidateField(modelProps) // When result is false meaning that the fields are not validatable if (result === true) { await callback?.(result) @@ -148,7 +149,7 @@ const validateField: FormContext['validateField'] = async ( formItem?.scrollIntoView(props.scrollIntoViewOptions) } } - await callback?.(false, invalidFields) + !result && (await callback?.(false, invalidFields)) return shouldThrow && Promise.reject(invalidFields) } }