javascriptformspromiseformvalidation.io

Looping through promises


I am trying to validate 10 form fields using formvalidation.io. If any of the 10 validations fail I need to return false. However to access whether a validation has passed or not you need to call a promise.

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

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

The above doesn't work because promises aren't synchronous.


Solution

  • You can map over your fields to create an array of promises. Use Promise.all to wait for those promises to resolve and then use every to check the response status of each validation.

    I've used async/await here but Promise.all(promises).then would work equally well. I've also mocked up a demo validation routine so you can see it in action. Simply change the resolve from 'Valid' to 'Invalid' and rerun the demo to see allValid equal 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);
      }
    })();