最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to require at least 1 checkbox for AngularJS Form Validation? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Oct 17, 2015 at 1:07 albert 8,1533 gold badges48 silver badges64 bronze badges asked Oct 17, 2015 at 1:04 ActivelyActively 1111 gold badge2 silver badges10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

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()">
发布评论

评论列表(0)

  1. 暂无评论