feat(Form): add validate-first prop

This commit is contained in:
陈嘉涵 2020-02-12 11:19:58 +08:00
parent 080d1828c8
commit 48d2f64aba
2 changed files with 56 additions and 13 deletions

View File

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

View File

@ -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;