How to trigger `validate` function for each component in an array?

Hello, I'm working on a form with many input elements in my app. I trigger a checkAllValidations JavaScript function when the end user clicks "Submit." This function returns true if all validations pass and false if any fail. I'm using a JS function because input fields may be dynamically added or removed based on the user’s previous selections.

const requiredComponents = [ input1, input2.... inputN]
//add or remove any component 
 
const validateAllInputs = async () => {
  const results = await Promise.all(
    requiredComponents.map(component => component.validate())
  );

  console.log(results)
  
  // Check if all validations passed
  return results.every(result => result === true);
};

// Usage
validateAllInputs().then(allValid => {
  console.log(allValid); // true if all inputs are valid, otherwise false
});

I always get false and the elements of result are always undefined.

Any advice?

1 Like

Hi @felipe

You need to return allValid when calling the validateAllInputs function.

Here's the revised code:

const requiredComponents = [ input1, input2.... inputN]
//add or remove any component 
 
const validateAllInputs = async () => {
  const results = await Promise.all(
    requiredComponents.map(component => component.validate())
  );

  console.log(results)
  
  // Check if all validations passed
  return results.every(result => result === true);
};

// Usage
validateAllInputs().then(allValid => {
  console.log(allValid); // true if all inputs are valid, otherwise false
  return allValid;
});
1 Like

that's true, I missed returning allValid. But I see the output in the console produced by console.log(allValid);. It says: {"input1": undefined, "input2": undefined.... "inputN": undefined }. So, something is not working properly.

1 Like

Hey @felipe! Welcome to the community. :slightly_smiling_face:

Your validations should automatically run on change to each input, meaning you only need to read whether they are valid or not using component.invalid. This runs synchronously and simply returns a boolean.

I hope that helps! Let me know if you have any follow-up questions.

2 Likes