如何为AngularJS表单验证至少要求1个复选框?

时间:2022-12-05 19:35:04

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.

我有一个JSON对象数组,显示在一个表单中。我希望进行表单验证工作,其中用户必须至少选中一个复选框才能使整个表单有效。

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.

我知道可以使用ng-required,但是对于我所拥有的实现,这意味着必须选择所有这些才能使其有效。

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?

关于我如何能够实现这种行为的任何想法?

1 个解决方案

#1


17  

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

您可以添加另一个范围属性并使用array.some检查是否有任何选定的属性。然后将该范围属性提供给ng-required。就像是

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

<input type="checkbox" value="" data-ng-model="item.selected" ng-required="isOptionsRequired()">

#1


17  

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

您可以添加另一个范围属性并使用array.some检查是否有任何选定的属性。然后将该范围属性提供给ng-required。就像是

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

<input type="checkbox" value="" data-ng-model="item.selected" ng-required="isOptionsRequired()">