diff --git a/src/field/index.js b/src/field/index.js index 8621c7206..e6a5d1604 100644 --- a/src/field/index.js +++ b/src/field/index.js @@ -135,19 +135,29 @@ export default createComponent({ } }, - // @exposed-api validate() { - if (!this.rules) { - return true; - } - - return !this.rules.some(rule => { - if (rule.required && !this.formValue) { - this.validateMessage = rule.message; - return true; + return new Promise(resolve => { + if (!this.rules) { + resolve(); } - return false; + const messages = []; + + this.rules.forEach(rule => { + if (rule.required && !this.formValue) { + messages.push(rule.message); + } + }); + + if (messages.length) { + this.validateMessage = messages[0]; + resolve({ + name: this.name, + messages, + }); + } else { + resolve(); + } }); }, diff --git a/src/form/index.js b/src/form/index.js index 8eb02fce3..1f062bebe 100644 --- a/src/form/index.js +++ b/src/form/index.js @@ -19,10 +19,20 @@ export default createComponent({ methods: { // @exposed-api validate() { - return this.fields.map(item => item.validate()).every(item => item); + return new Promise((resolve, reject) => { + Promise.all(this.fields.map(item => item.validate())).then(errors => { + errors = errors.filter(item => item); + + if (errors.length) { + reject(errors); + } else { + resolve(); + } + }); + }); }, - getFormData() { + getValues() { return this.fields.reduce((form, field) => { form[field.name] = field.formValue; return form; @@ -32,13 +42,18 @@ export default createComponent({ onSubmit(event) { event.preventDefault(); - const valid = this.validate(); + const values = this.getValues(); - if (valid) { - this.$emit('submit', this.getFormData()); - } else { - this.$emit('failed'); - } + this.validate() + .then(() => { + this.$emit('submit', values); + }) + .catch(errors => { + this.$emit('failed', { + values, + errors, + }); + }); }, }, diff --git a/vant.config.js b/vant.config.js index 2d32daf19..b20f0c729 100644 --- a/vant.config.js +++ b/vant.config.js @@ -126,6 +126,10 @@ module.exports = { path: 'field', title: 'Field 输入框', }, + { + path: 'form', + title: 'Form 表单', + }, { path: 'number-keyboard', title: 'NumberKeyboard 数字键盘', @@ -461,6 +465,10 @@ module.exports = { path: 'field', title: 'Field', }, + { + path: 'form', + title: 'Form', + }, { path: 'number-keyboard', title: 'NumberKeyboard',