diff --git a/src/field/index.js b/src/field/index.js index 9db45eb60..00dc4921f 100644 --- a/src/field/index.js +++ b/src/field/index.js @@ -3,7 +3,7 @@ import { formatNumber } from './utils'; import { isIOS } from '../utils/validate/system'; import { preventDefault } from '../utils/dom/event'; import { resetScroll } from '../utils/dom/reset-scroll'; -import { createNamespace, isObject, isDef, addUnit } from '../utils'; +import { createNamespace, isObject, isDef, addUnit, isPromise } from '../utils'; // Components import Icon from '../icon'; @@ -151,31 +151,41 @@ export default createComponent({ resolve(); } - const messages = []; - - this.rules.forEach(rule => { - if (rule.required && this.formValueEmpty) { - messages.push(rule.message); - } - - if (rule.validator) { - const result = rule.validator(this.formValue); - - if (!result) { - messages.push(rule.message); + Promise.all( + this.rules.map(rule => { + if (rule.required && this.formValueEmpty) { + return Promise.resolve(rule.message); } + + if (rule.validator) { + const returnVal = rule.validator(this.formValue); + + if (returnVal === false) { + return Promise.resolve(rule.message); + } + + if (isPromise(returnVal)) { + return returnVal.then( + result => result === false && rule.message + ); + } + } + + return Promise.resolve(); + }) + ).then(messages => { + messages = messages.filter(item => item); + + if (messages.length) { + this.validateMessage = messages[0]; + resolve({ + name: this.name, + messages, + }); + } else { + resolve(); } }); - - if (messages.length) { - this.validateMessage = messages[0]; - resolve({ - name: this.name, - messages, - }); - } else { - resolve(); - } }); }, diff --git a/src/form/README.md b/src/form/README.md index 77a687a8c..c21cf0f99 100644 --- a/src/form/README.md +++ b/src/form/README.md @@ -52,6 +52,43 @@ export default { } ``` +### Validate Rules + +```html + + +
+ Submit +
+
+``` + +```js +export default { + data() { + this.rules = [ + { required: true, message: 'Phone is required' }, + { validator: val => /1\d{10}/.test(val), message: 'Incorrect format' }, + ]; + return { value: '' }; + }, + methods: { + onSubmit(values) { + console.log('submit', values); + }, + onFailed(errorInfo) { + console.log('failed', errorInfo); + }, + }, +}; +``` + ### Field Type - Switch ```html diff --git a/src/form/README.zh-CN.md b/src/form/README.zh-CN.md index b0acfb340..d1dc67c46 100644 --- a/src/form/README.zh-CN.md +++ b/src/form/README.zh-CN.md @@ -60,17 +60,16 @@ export default { ### 校验规则 -在`rules`中,可以通过`validator`字段定义校验函数,校验函数返回`false`时表示校验不通过 +在`rules`中,可以通过`validator`字段定义校验函数,校验函数返回`false`时表示校验不通过,返回`Promise`时表示异步校验 ```html - +
提交 diff --git a/src/form/demo/ValidateRules.vue b/src/form/demo/ValidateRules.vue index 689bb7f31..09b04a6b2 100644 --- a/src/form/demo/ValidateRules.vue +++ b/src/form/demo/ValidateRules.vue @@ -1,13 +1,19 @@