使用范围验证validateAll

使用范围验证validateAll

本文介绍了Vee-使用范围验证validateAll()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我已经对表单进行了划分(范围限定),以便我可以使用以下函数一次验证小块。

I have a scenario where I have sectioned out (scoped) a form so that I can validate small chunks at a time using the following function.

validateScope (scope) {
  return this.$validator.validateAll(scope);
}

我希望在提交之前对整个表单进行一次最终验证服务器;但是,validateAll()似乎没有获取已添加到范围的输入。我也试过验证每个范围,然后提交表格,如果它们都是有效的,但我不知道该怎么做,因为一切都是异步的。

I want to do one final validation of the entire form before I submit it to the server; however, validateAll() doesn't seem to pick up inputs that have been added to a scope. I've also tried just validating each scope and then submit the form if they are ALL valid, but I am not sure how to do that since everything is asynchronous.

validateAll () {
   let valid = true;

   // Not sure how to build this function since validateScope is asynchronous
   _.each(this.names, (name, index) => {
     if(this.validateScope('name-' + index)){
       valid = false;
     }
   });

   return valid; // Always returns true even though the _.each should set it to false
}


推荐答案

正如我的评论所述,您的代码最终会看起来像这样:

As mentioned in my comment, your code will end up looking something like this:

validateAll () {
   let valid = true;

   let validations = []
   _.each(this.names, (name, index) => {
     validations.push(this.validateScope('name-' + index))
   });

   return Promise.all(validations)
     // consolidate the results into one Boolean
     .then(results => results.every(r => r))
}

然后,当然,你必须使用 validateAll 作为承诺:

Then, of course, you'll have to use validateAll as a promise:

this.validateAll().then(isValid => {
  if (!isValid) {
    //do whatever you need to do when something failed validation
  } else {
    // do whatever you need to do when everything is valid here
  }
})

这篇关于Vee-使用范围验证validateAll()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:40