0

I have a set of checkboxes in a form. How can I validate the form when at least one of them is checked?

<div class="col-lg-9 col-md-9 col-sm-9 col-xs-9" ng-init="row.user_input = {}">
    <div ng-repeat="value in row.allowed_values" class="checkbox-inline">
        <input type="checkbox"
               name="{{row.field}}"
               value="{{value}}"
               ng-model="row.user_input[value]"
               ng-required="{{row.mandatory_field && !someSelected(row.user_input)}}">{{value | capitalize}}
    </div>
</div>

Here a whole bunch of details.

1 Answer 1

1

Check out this working plunkr: https://plnkr.co/edit/5H73o70p4ONz4jxGiY4e?p=preview

  $scope.input={
    values: {
      'a': false,
      'b': false,
      'c': false
    }
  };
  $scope.someSelected = function(values) {
    for(var value in values) {
      if(values[value]) {
         return true;
      }
    }
    return false;
  }

You can save the user input as object rather than array to check if at least one is checked. In the view:

<form name="checkboxTest">
    <div ng-repeat="(key,value) in input.values">
        <input type="checkbox"
           name="checkbox"
           value="{{value}}"
           ng-model="input.values[key]"
           ng-required="!someSelected(input.values)">
        {{key}}
    </div>
    <pre>
    {{input}}
    </pre>
    <button type="submit" ng-disabled="!checkboxTest.$valid">Submit</button>
</form>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.