Home Angular1 Custom Validator: Require one checkbox be selected
Reply: 0

Angular1 Custom Validator: Require one checkbox be selected

schnauss
1#
schnauss Published in 2017-11-14 18:08:43Z

I'm trying to figure out a way to make an Angular 1.6 checkbox group nested inside an ngForm require at least one checkbox be selected. Is there a good way of doing this?

The list of checkboxes is not hard-coded, but rather determined by a secondary data model (see params.options in the JS) which keeps track of which display labels correspond to which ID numbers.

I have created a Plunker here which demonstrates the issue at hand and what I have so far.

Any help on this would be appreciated! This seems to be something that was skipped over when Angular1 form validation was being developed.

HTML:

  <body ng-app="app" ng-controller="AppController">
    <h1>{{params.appName}}</h1>

    <div class="container" ng-form="containerForm">
      <p>We want to set up validation so that at least 1 option must be selected.</p>
        <div ng-repeat="option in params.options" class="col-xs-12 col-sm-6 col-lg-4">
            <label>
                <input type="checkbox" ng-model="params.results[option.id]" ng-true-value="'{{option.id}}'" ng-false-value="null"> {{option.value}}
            </label>
        </div>
    </div>

    <p>
      <strong>Form validity:</strong>
    </p>

    <pre>
      {{containerForm | json}}
    </pre>


    <p>
      <strong>Resulting data model:</strong>
    </p>

    <pre>
      {{params.results | json}}
    </pre>

  </body>

JavaScript:

var app = angular.module('app', [])
.controller('AppController', function($scope){
  $scope.params = {
    appName: "Angular1 Multiselect Validation",
    // List of the different options that can be selected
    options: [{
      id: 0,
      value: 'Option 0',
    },{
      id: 1,
      value: 'Option 1',
    },{
      id: 2,
      value: 'Option 2',
    },],

    // Result list in the format expected by the server
    results: []
  }
})
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.3144 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO