简体   繁体   中英

How can I compare if the inputs are empty or not of an object within an array

这些是输入

Im trying to loop an array and compare if all objects values are not empty, in case of all inputs(object value) are not empty go to next step, otherwise show error.

Clicking on 'Agregar' Button should loop the array and see if inputs are empty or not'

Here is the code:

const onAdd = () => {

 var match = false;
 for (let index = 0; index <= entities.length; index++) {   

  entities.map((value) => {
    if (
      value.entityName?.trim() == "" ||
      value.personInCharge?.trim() == "" ||
      value.emailPersonInCharge?.trim() == ""
    ) {
      match = true;
    } else {
      match = false;
    }
   
  });
}

if (match) {
  toast.error(
    "Completa todos los campos o marque la casilla de `Solo una compañia` "
  );
} else {
  entities.push(defaultFields);

  const newData = entities.map((d, index) => {
    return d;
  });

  setData({ entities: newData });
  setData({ ...dataNewChannel, entities: newData });
 
}

}

try this

const form = [{}, {}, {}];

function validate(form) {
  const keys = Object.keys({
    entityName: '',
    personInCharge: '',
    emailPersonInCharge: ''
  });
  let errors = [];
  for (let i = 0; i < form.length; i++) {
    let hasError = false;
    for (let j = 0; j < keys.length; j++) {
      if (!form[i][keys[j]] || form[i][keys[j]].trim() === '') {
        hasError = true;
        errors.push(`form [${i}] ${keys[j]} is empty`);
        break;
      }
    }
    if (hasError) {
      break;
    }
  }
  return errors;
}

const err = validate(form); // [ 'form [0] entityName is empty' ]
if (err) {
  alert(err[0]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM