fix(components): [form] the validate function is executed repeatedly (#19345)

This commit is contained in:
betavs
2025-06-07 10:30:26 +08:00
committed by GitHub
parent eb342b511e
commit cbc11e601d
2 changed files with 47 additions and 2 deletions

View File

@@ -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 () => (
<Form ref="formRef" model={form} rules={rules.value}>
<FormItem ref="age" prop="age" label="age">
<Input v-model={form.age} />
</FormItem>
</Form>
)
},
})
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()

View File

@@ -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)
}
}