7

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

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

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

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
}
4

1 回答 1

6

正如我在评论中提到的,您的代码最终看起来像这样:

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作为一个承诺:

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
  }
})
于 2018-02-28T15:28:24.200 回答