AngularJS group check box validation

If you want to require at least one item in group being selected, it’s possible to define dynamic required attribute with ng-required.

For gender radio buttons this would be easy:

<input
    type="radio"
    ng-model="formData.selectedGender"
    value="{{val.id}}"
    ng-required="!formData.selectedGender"
>

Checkbox group would be easy too, if you used array to store selected fruits (just check array length), but with object it’s necessary to check if any of values are set to true with filter or function in controller:

$scope.someSelected = function (object) {
  return Object.keys(object).some(function (key) {
    return object[key];
  });
}
<input
    type="checkbox"
    value="{{val.id}}"
    ng-model="formData.selectedFruits[val.id]"
    ng-required="!someSelected(formData.selectedFruits)"
>

Update:

const someSelected = (object = {}) => Object.keys(object).some(key => object[key])

Also keep in mind that it will return false if value is 0.

Leave a Comment