check if object items are empty

0

Hello, I have an object that receives parameters from a form and sends that object to another page. On this page I need to validate if at least three items have been filled out. Could someone help me?

    
asked by anonymous 05.12.2016 / 19:04

1 answer

3

You can cycle through object values using for..in and save to a counter. If the counter is greater than 2, it means that at least 3 values have been filled. Example:

var obj = {
    "param1": "1",
    "param2": "2",
    "param3": "",
    "param4": "",
    "param5": ""
  },
  cont = 0;

for (propriedade in obj) {
  // retorna true se o valor for diferente de undefined, vazio, null, zero, espaços
  if (obj[propriedade])
    cont++;
}

if (cont > 2)
  alert("Pelo menos 3 preenchidos")
else
  alert("Falta à preencher");
    
05.12.2016 / 19:10