How can I validate checkbox in angularjs?


Usually I use formName.inputName.$invalid to show error message input like this:

<input name="myInput" minlength="3" />
<span ng-show="myForm.myInput.$invalid">too short</span>

that won't be a problem.

But when I tried to validate checkbox,it seems difficult, there are the snippet at the end.

I want the effect that user should at least check one checkbox ,or you got the warning message.

How can I do that in a simple way at best?

// app.js

var formApp = angular.module('formApp', [])

    .controller('formController', function($scope) {

        // we will store our form data in this object
        $scope.formData = {};

        $scope.formData.favoriteColors = [{
            'id':'1',
            'name':'red'
        },{
            'id':'2',
            'name':'green'
        },{
            'id':'3',
            'name':'blue'
        }];

        $scope.cList = [];
        $scope.checkList = function(index){
            if($scope.myForm.favoriteColors.$pristine){
                $scope.cList.push($scope.formData.favoriteColors[index]);
            }
            else{
                angular.forEach($scope.formData.favoriteColors,function(value,key){
                    if(value.checked){
                        $scope.cList.push(value.id);
                    }
                });
            }
            console.log('cList:%o',$scope.cList);
        };

    });
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>

    <!-- CSS -->
    <!-- load up bootstrap and add some spacing -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
    <link href="http://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
    <style>
        body         { padding-top:50px; }
        form         { margin-bottom:50px; }
    </style>

    <!-- JS -->
    <!-- load up angular and our custom script -->
    <script src="lib/angular/angular.min.js"></script>
    <script src="app.js"></script>
</head>

<!-- apply our angular app and controller -->
<body ng-app="formApp" ng-controller="formController">
<div class="col-xs-12 col-sm-10 col-sm-offset-1">

    <h2>Angular Checkboxes and Radio Buttons</h2>

    <form name="myForm">
        <!-- NAME INPUT -->
        <div class="form-group">
            <label>Name</label>
            <input type="text" class="form-control" name="name" ng-model="formData.name">
        </div>
        <!-- MULTIPLE CHECKBOXES -->
        <label>Favorite Colors</label>
        <div class="form-group">
            <label class="checkbox-inline" ng-repeat="color in formData.favoriteColors">
                <input type="checkbox" name="favoriteColors" ng-model="color.checked" ng-click="checkList($index)" required>{{color.name}}
            </label>
            <span class="danger" ng-show="myForm.favoriteColors.$invalid">Please check one color at least</span>
        </div>

        <!-- SUBMIT BUTTON (DOESNT DO ANYTHING) -->
        <button type="submit" class="btn btn-danger btn-lg">Send Away!</button>
    </form>

    <!-- SHOW OFF OUR FORMDATA OBJECT -->
    <h2>Sample Form Object</h2>
    <pre>
        dirty:{{ myForm.favoriteColors.$dirty }}
        pristine:{{ myForm.favoriteColors.$pristine }}
        valid:{{ myForm.favoriteColors.$valid }}
        invalid:{{ myForm.favoriteColors.$invalid }}
        error:{{ myForm.favoriteColors.$error }}
    </pre>

</div>
</body>
</html>

Here is the live demo:http://jsbin.com/yigujoporu/1/

I use a count funtcion to update the number of checked checkbox.

Here is the live demo:http://jsbin.com/wowipi/4/edit?js,output


You can custom validation by another way First, in your controller

            $scope.cList = [];
            $scope.checked = false;
            $scope.checkList = function(index){
                if($scope.myForm.favoriteColors.$pristine){
                    $scope.cList.push($scope.formData.favoriteColors[index]);
                }
                else{

                    if($scope.formData.favoriteColors[index].checked == true){
                    //checked
                   $scope.cList.push($scope.formData.favoriteColors[index]);
                   }else{
                   //uncheck
                   angular.forEach($scope.cList, function(value,key){
                      if($scope.formData.favoriteColors[index].id == value.id){
                      //remove it
                      $scope.cList.splice(key,1);
                      }
                   }
               }

                console.log('cList:%o',$scope.cList);
                //new change
                if($scope.cList.length >0) {
                    $scope.checked = true;
                }else{
                     $scope.checked = false;
                }
            };

In your view

<div class="form-group">
    <label class="checkbox-inline" ng-repeat="color in formData.favoriteColors">
         <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors[$index].checked" ng-click="checkList($index)" required>{{color.name}}
    </label>
    <span class="danger" ng-show="!checked">Please check one color at least</span>
</div>