user1760110 user1760110 - 13 days ago 5
Javascript Question

Issue on Validating an JS Object with Boolean Properties

I am trying to validate an object which contains some Boolean properties. The code is suppose to loop in the

validate
object and return
TRUE
if ALL of options are
true
and
FALSE
if ANY of the options are
false
.



var validate = {
text: true,
email: true,
phone: false
};

for (var key in validate) {
if (validate[key] == false) {
console.log("Not Valid");
break;
} else {
console.log("Yes Object is Valid");
}

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>





As you can see apparently I am not getting correct return. Can you please let me know how to fix this?

Answer
var all_valid = true;

for (var key in validate) {
  if (validate[key] == false) {
    console.log("Not Valid");
    all_valid = false;
    break;
  }
}

if(all_valid) {
    console.log("Yes Object is Valid");
}