Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require at least 1 checkbox for AngularJS Form Validation?

I have an array of JSON objects which is displayed in a form. I would like to have the form validation work where a user has to select at least one checkbox for the entire form to be valid.

I know that the ng-required can be used but with the implementation I have, it means that all of them have to be selected for it to be valid.

Here is the code I have so far:

index.html:

<div ng-repeat="item in volunteerOptions">
    <label class="checkbox"><input type="checkbox" value="" data-ng-model="item.selected" ng-required="true">{{ item.content }}</label>
</div>

<button type="submit" class="btn btn-success" ng-disabled="!memberRegistrationForm.$valid">Submit</button>

controller.js

$scope.volunteerOptions = [
        { content : 'Content 1', selected : false },
        { content : 'Content 2', selected : false },
        { content : 'Content 3', selected : false },
        { content : 'Content 4', selected : false },
];

Any ideas on how I would be able to achieve this behaviour?

like image 611
Actively Avatar asked Oct 17 '15 01:10

Actively


People also ask

Does required attribute work for checkbox?

The required attribute is supported by text , search , url , tel , email , password , date , month , week , time , datetime-local , number , checkbox , radio , file , <input> types along with the <select> and <textarea> form control elements.

How is validation done in AngularJS?

AngularJS performs form validation on the client side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not.

What is used for validating AngularJS forms?

AngularJS offers client-side form validation. AngularJS monitors the state of the form and input fields (input, textarea, select), and lets you notify the user about the current state. AngularJS also holds information about whether they have been touched, or modified, or not.


1 Answers

You can add another scope property and use array.some to check if any of the selected are true. Then feed that scope property to ng-required. Something like

$scope.isOptionsRequired = function(){
  return !$scope.volunteerOptions.some(function(options){
    return options.selected;
  });
}

<input type="checkbox" value="" data-ng-model="item.selected" ng-required="isOptionsRequired()">
like image 63
Joseph Avatar answered Sep 21 '22 12:09

Joseph