1

I am trying to create a validation in my app.

What I have, is multiple lists with a toggle (true/false).

If the item is selected, it populates an array.

And I have a different array for each group.

Pretty much something like this:

$scope.selected = {
  group1: {
    values: []
  },
  group2: {
    values: []
  },
  group3: {
    values: []
  }
}

When I select something, let's say, from the list in group 1, $scope.selected changes to this:

$scope.selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   }
}

The problem I've got is that I am trying to validate this.

What I need is to be able to display a message if multiple values arrays are greater than 0.

For instance if:

$scope.selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   },
   group2: {
     values: [{cat: 2, id: 5},{cat:2, id:2}]
   }
}

a message should appear as I can't allow to submit multiple groups at once.

I know that I can have some sort of function that checks on the specific name for the groups, but I need something a bit more dynamic, as groups may (and will) increase at some point (ie. I will have more groups that the ones I have now).

Is there any way I can check that only one out of all my group arrays is not empty, and if multiple are not empty, I show something?

thanks and I hope it's clear enough

1
  • Working, minimal code snippet would be helpful. Commented Mar 29, 2017 at 9:22

2 Answers 2

1

You can iterate through the object:

var count = 0;
for (var group in $scope.selected) {
   if ($scope.selected.hasOwnProperty(group) && group.values.length > 0) 
      count++;
}

if (count > 1)
   console.log("More than one group with values");
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Array#filter and Object.keys(o)

const selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   },
   group2: {
     values: [{cat: 2, id: 5},{cat:2, id:2}]
   }
};
const validSelected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   },
   group2: {
     values: []
   }
};

function validate(obj){
  return Object.keys(obj).filter(k=>obj[k].values.length>0).length === 1;
}



console.log(validate(selected)); //false
console.log(validate(validSelected)); //true

Without ES6 arrow :

Object.keys(obj).filter(function(k){return obj[k].values.length>0).length === 1});

1 Comment

I am using CoffeeScript and the arrow function is a bit tricky to convert...can I have an example that doesn't use the arrow function please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.