互斥复选框的验证失败

时间:2016-07-20 07:56:13

标签: angularjs

我有两个复选框。验证条件在form-submit上,当且仅当选中一个复选框时,表单才有效。

这样做了。给两个复选框提供相同的类名,然后在ng-click上循环选中复选框,找到这样的复选计数。

$scope.SetCheckDatesCount = function () {
    $scope.CheckedDatesCount = 0;
    var checkBoxes = document.getElementsByClassName("AcceptedChecks");
    for (var i = 0; i < checkBoxes.length; i++) {
        if (checkBoxes[i].checked) {
            $scope.CheckedDatesCount++;
        }
    }
};

现在我在标记中设置了

ng-required="CheckedDatesCount != 1"

因此,在CheckedDatesCount = 0 ||CheckedDatesCount = 2时,该复选框将是必需的。

但如果我选中两个复选框,验证将无效。

Plunkr演示:https://plnkr.co/edit/ekGCpdXspQAf6zTwDToT?p=preview

我可以通过使用这样的额外支票来停止表单提交。 (但这很干净吗?)

if (theForm.$invalid && CheckedDatesCount != 1) {
    $scope.showMessages = true;
    return;
}

选中两个复选框时,为什么表单无效。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您无需检查检查框的状态。我想你可以这样做 -

<body ng-app="app" ng-controller="DemoController">

        <div class="container" ng-form="DemoForm">
          <div class="row">
            <div class="col-md-6">
              <label>Is Interview Date Accepted: </label>
              <input type="checkbox" class="AcceptedChecks" name="InterviewAccepted" ng-model="Interview.InterviewAccepted" ng-required="1 && !Interview.AlternateAccepted" ng-click="SetCheckDatesCount()" />
            </div>
            <div class="col-md-6">
              <label>Is Alternate Date Accepted: </label>
              <input type="checkbox" class="AcceptedChecks" name="AlternateAccepted" ng-model="Interview.AlternateAccepted" ng-required="1 && ! Interview.InterviewAccepted" ng-click="SetCheckDatesCount()" />
            </div>
          </div>

          <div class="row">
            <button class="btn btn-success" ng-click="AcceptInterview(DemoForm)">
              Accept
            </button>
          </div>
        </div>
      </body>

    </html>
    <script>
    // Code goes here
    var app = angular.module("app", []);

    app.controller("DemoController", ["$scope", function($scope){
      $scope.showMessages = false;
      $scope.Interview = {
        AlternateAccepted: false,
        InterviewAccepted: false
      };


      $scope.AcceptInterview = function (theForm) {
        console.log(theForm.$invalid);
        if (theForm.$invalid) {
            $scope.showMessages = true;
            return;
        }
        alert("valid");
      }
    }]);

    </script>

或者你可以这样做: -

<html>
  <div disabled="disabled">
    <h1 tabindex="0">Hello Disabled Div</h1>
  </div>
  <div>
    <h1 tabindex="0">Hello 2</h1>
  </div>
</html>