diff --git a/src/form/demo/ValidateRules.vue b/src/form/demo/ValidateRules.vue index 09b04a6b2..d3834df7d 100644 --- a/src/form/demo/ValidateRules.vue +++ b/src/form/demo/ValidateRules.vue @@ -30,8 +30,9 @@ export default { phone: '手机号', title: '校验规则', submit: '提交', - required: '请输入手机号', validating: '验证中...', + requireCode: '请输入验证码', + requirePhone: '请输入手机号', incorrectCode: '验证码错误', incorrectPhone: '手机号格式错误', }, @@ -41,6 +42,8 @@ export default { title: 'Validate Rules', submit: 'Submit', validating: 'Validating...', + requireCode: 'Code is required', + requirePhone: 'Phone is required', incorrectCode: 'Incorrect code', incorrectPhone: 'Incorrect phone', }, @@ -56,23 +59,16 @@ export default { created() { this.rules = { phone: [ - { required: true, message: this.$t('required') }, + { required: true, message: this.$t('requirePhone') }, { validator: val => /1\d{10}/.test(val), message: this.$t('incorrectPhone'), }, ], code: [ + { required: true, message: this.$t('requireCode') }, { - validator: val => - new Promise(resolve => { - this.$toast.loading(this.$t('validating')); - - setTimeout(() => { - this.$toast.clear(); - resolve(/\d{6}/.test(val)); - }, 1000); - }), + validator: this.validateCode, message: this.$t('incorrectCode'), }, ], @@ -80,6 +76,17 @@ export default { }, methods: { + validateCode(val) { + return new Promise(resolve => { + this.$toast.loading(this.$t('validating')); + + setTimeout(() => { + this.$toast.clear(); + resolve(/\d{6}/.test(val)); + }, 1000); + }); + }, + onSubmit(values) { console.log('submit', values); }, diff --git a/src/form/index.js b/src/form/index.js index 577e85fe8..7cb18a2fc 100644 --- a/src/form/index.js +++ b/src/form/index.js @@ -3,6 +3,10 @@ import { createNamespace } from '../utils'; const [createComponent, bem] = createNamespace('form'); export default createComponent({ + props: { + validateFirst: Boolean, + }, + provide() { return { vanForm: this, @@ -16,8 +20,35 @@ export default createComponent({ }, methods: { - // @exposed-api - validate() { + validateSeq() { + return new Promise((resolve, reject) => { + const errors = []; + + this.fields + .reduce( + (promise, field) => + promise.then(() => { + if (!errors.length) { + return field.validate().then(error => { + if (error) { + errors.push(error); + } + }); + } + }), + Promise.resolve() + ) + .then(() => { + if (errors.length) { + reject(errors); + } else { + resolve(); + } + }); + }); + }, + + validateAll() { return new Promise((resolve, reject) => { Promise.all(this.fields.map(item => item.validate())).then(errors => { errors = errors.filter(item => item); @@ -31,6 +62,11 @@ export default createComponent({ }); }, + // @exposed-api + validate() { + return this.validateFirst ? this.validateSeq() : this.validateAll(); + }, + getValues() { return this.fields.reduce((form, field) => { form[field.name] = field.formValue;