【问题标题】:How to require at least 1 checkbox for AngularJS Form Validation?如何要求至少 1 个复选框用于 AngularJS 表单验证?
【发布时间】:2016-01-15 20:44:50
【问题描述】:

我有一个以表单形式显示的 JSON 对象数组。我想让表单验证工作,用户必须选择至少一个复选框才能使整个表单有效。

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

这是我目前的代码:

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 },
];

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

【问题讨论】:

    标签: javascript angularjs forms validation


    【解决方案1】:

    您可以添加另一个范围属性并使用array.some 来检查任何selected 是否为true。然后将该范围属性提供给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()">
    

    【讨论】:

    • 谢谢这是完美的。
    • 这工作正常。但是如何在复选框下方显示错误消息。我使用了这个 - &lt;div ng-show="projectForm.$submitted || projectForm.item_id.$touched"&gt; &lt;span ng-show="projectForm.item_id.$error.required" class="text-danger"&gt;Select any Item.&lt;/span&gt; &lt;/div&gt; 这个错误消息工作正常,但是当我在复选框名称属性中应用 item_id 时。当我检查任何一个时,我都检查了。请帮帮我...
    猜你喜欢
    • 1970-01-01
    • 2016-09-11
    • 2017-05-30
    • 1970-01-01
    • 2018-04-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多