如何为AngularJS表单验证至少要求1个复选框? [英] How to require at least 1 checkbox for AngularJS Form Validation?

查看:139
本文介绍了如何为AngularJS表单验证至少要求1个复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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?

推荐答案

您可以添加另一个范围属性并使用 array.some 来检查是否有任何选中 true 。然后将该范围属性提供给 ng-required 。类似于

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()">

这篇关于如何为AngularJS表单验证至少要求1个复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆