From 3a7f981b966119faf77dd5ee9c6db3b094c26037 Mon Sep 17 00:00:00 2001 From: homi <1572801584@qq.com> Date: Thu, 9 Jan 2025 17:18:08 +0800 Subject: [PATCH] fix: form onValueChange validate time series problem (#1372) * fix: form onValueChange validate time series problem * fix: form onValueChange validate time series problem --- demo/pages/Form/FormBasic/index.ts | 22 ++++++++++++++++++++-- src/Form/form.ts | 11 ++++++++++- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/demo/pages/Form/FormBasic/index.ts b/demo/pages/Form/FormBasic/index.ts index 48a5f4686..8c04bd0c7 100644 --- a/demo/pages/Form/FormBasic/index.ts +++ b/demo/pages/Form/FormBasic/index.ts @@ -36,12 +36,30 @@ Page({ onLoad() { this.form = new Form({ initialValues: { user: { account: 'andy', phone: '10000' } }, + rules: { + account: [ + { + required: true, + message: '请输入账号', + }, + () => ({ + // 一定需要时异步函数,返回Promise对象 + validator: async (_, value) => { + if (value.length !== 11) { + throw new Error('请输入正确的账号'); + } + }, + }), + ], + }, }); this.form.onValueChange('user.account', (value, allValues) => { - console.log('onValueChange:', value, allValues); + const validates = this.form.getFieldsValidatorStatus(); + console.log('onValueChange:', value, allValues, validates); }); this.form.onValuesChange((value, allValues) => { - console.log('onValuesChange:', value, allValues); + const validates = this.form.getFieldsValidatorStatus(); + console.log('onValuesChange:', value, allValues, validates); }); /// #if WECHAT if (this.formRefList) { diff --git a/src/Form/form.ts b/src/Form/form.ts index a3282637c..a50ee882c 100644 --- a/src/Form/form.ts +++ b/src/Form/form.ts @@ -126,11 +126,20 @@ class Field extends EventEmitter { message, validateTrigger ); - this.ref.on((trigger, value, extraInfo?: any) => { + this.ref.on(async (trigger, value, extraInfo?: any) => { if (trigger === 'onChange') { this.setValue(value); this.touched = true; + // 触发校验,需要在 onValueChange 之前执行 + await Promise.all( + this.validateTrigger.map((item) => { + if (item === trigger) { + return this.validate(); + } + }) + ); this.emit('valueChange', value); + return; } else if (trigger === 'didUnmount') { this.emit('didUnmount'); } else if (trigger === 'deriveDataFromProps') {