1

我正在尝试使用 formvalidation.io 验证 10 个表单字段。如果 10 个验证中的任何一个失败,我需要返回 false。但是,要访问验证是否已通过,您需要调用一个 Promise。

var otherFacilityFields = [
    "addressLine1",
    "city"
];

  fieldsPass = otherFacilityFields.every(function(field) {
    fv.validateField(field).then(function(status) {
        if (status != 'Valid') {
            return false;
        }
        return true;
    });
  });

以上不起作用,因为承诺不是同步的。

4

2 回答 2

3

您可以map在您的字段上创建一系列承诺。用于Promise.all等待这些承诺解决,然后用于every检查每个验证的响应状态。

我在这里使用过async/ await,但Promise.all(promises).then效果同样好。我还模拟了一个演示验证例程,以便您可以看到它的实际效果。只需将解析从 'Valid' 更改为 'Invalid' 并重新运行演示以查看allValidequal false

const fv = {
  validateField() {
    return new Promise(resolve => {
      setTimeout(() => resolve('Valid'), 1000);
    });
  }
}

const otherFacilityFields = ['addressLine1', 'city'];

// `map` over the fields and return a
// validation promise for each
const promises = otherFacilityFields.map(field => {
  return fv.validateField(field);
});

(async () => {
  try {

    // await the promises to all resolve
    const res = await Promise.all(promises);

    // Use `every` to check the status of each validation
    const allValid = res.every(status => status === 'Valid');
    console.log(allValid);
  } catch (e) {
    console.log(e);
  }
})();

于 2019-01-24T00:24:10.673 回答
0

如果您使用的 javascript 具有 async 和 await 您可以执行类似的操作

fieldsPass = otherFacilityFields.every(async function(field) {
    let status = await fv.validateField(field)
    if (status != 'Valid') {
        return false;
    }
    return true;
  });

或者您可以使用 Promise.all() 尝试一些解决方案,
或者您可以使用全局变量,例如

  let valid = true
  let length = otherFacilityFields.length
  fieldsPass = otherFacilityFields.every(function(field) {
    fv.validateField(field).then(function(status) {
        if (status != 'Valid') {
            valid = false;
        }
        valid = true;
        length = length - 1
        if(length == 0)
          //return the valid value
    });
  });

于 2019-01-24T00:18:20.173 回答