chore(Field): split validate method

This commit is contained in:
陈嘉涵 2020-02-12 17:05:23 +08:00
parent dd11f17693
commit f204a9871a
3 changed files with 57 additions and 49 deletions

View File

@ -63,7 +63,7 @@ export default createComponent({
watch: {
value() {
this.resetValidate();
this.resetValidation();
this.$nextTick(this.adjustSize);
},
},
@ -145,52 +145,54 @@ export default createComponent({
}
},
runValidator(validator) {
return new Promise(resolve => {
const returnVal = validator(this.formValue);
if (isPromise(returnVal)) {
return returnVal.then(resolve);
}
resolve(returnVal);
});
},
runRules() {
return this.rules.reduce(
(promise, rule) =>
promise.then(() => {
if (this.validateMessage) {
return;
}
if (rule.required && this.formValueEmpty) {
this.validateMessage = rule.message;
return;
}
if (rule.validator) {
return this.runValidator(rule.validator).then(result => {
if (result === false) {
this.validateMessage = rule.message;
}
});
}
}),
Promise.resolve()
);
},
validate() {
return new Promise(resolve => {
if (!this.rules) {
resolve();
}
let message;
this.rules
.reduce(
(promise, rule) =>
promise.then(() => {
if (message) {
return;
}
if (rule.required && this.formValueEmpty) {
({ message } = rule);
return;
}
if (rule.validator) {
const returnVal = rule.validator(this.formValue);
if (returnVal === false) {
({ message } = rule);
return;
}
if (isPromise(returnVal)) {
return returnVal.then(result => {
if (result === false) {
({ message } = rule);
}
});
}
}
}),
Promise.resolve()
)
.then(() => {
if (message) {
this.validateMessage = message;
this.runRules().then(() => {
if (this.validateMessage) {
resolve({
name: this.name,
message,
message: this.validateMessage,
});
} else {
resolve();
@ -199,7 +201,7 @@ export default createComponent({
});
},
resetValidate() {
resetValidation() {
if (this.validateMessage) {
this.validateMessage = '';
}

View File

@ -24,7 +24,13 @@ exports[`renders demo correctly 1`] = `
<div class="van-cell van-field">
<div class="van-cell__title van-field__label"><span>手机号</span></div>
<div class="van-cell__value van-field__value">
<div class="van-field__body"><input type="text" placeholder="手机号" class="van-field__control"></div>
<div class="van-field__body"><input type="text" name="phone" placeholder="手机号" class="van-field__control"></div>
</div>
</div>
<div class="van-cell van-field">
<div class="van-cell__title van-field__label"><span>验证码</span></div>
<div class="van-cell__value van-field__value">
<div class="van-field__body"><input type="text" name="code" placeholder="验证码" class="van-field__control"></div>
</div>
</div>
<div style="margin: 16px 16px 0px;"><button class="van-button van-button--info van-button--normal van-button--block van-button--round"><span class="van-button__text">提交</span></button></div>

View File

@ -8,7 +8,7 @@ export const FieldMixin = {
watch: {
value() {
if (this.vanField) {
this.vanField.resetValidate();
this.vanField.resetValidation();
}
},
},