checkbox unchecked to make form invalid

user2727195 picture user2727195 · Jan 20, 2015 · Viewed 7.8k times · Source

trying to add form validators for the checkbox in my form, in case if it's unchecked the form will have ng-invalid.

<li class="terms_checkbox"><input type="checkbox" id="checkbox_terms" name="terms" /><label for="checkbox_terms"></label></li>
<li class="accept">I have read and accept the terms and conditions</li>

any advise on what can trigger the addition of ng-invalid to the form if it's unchecked and vice versa for the class removal.

Answer

PSL picture PSL · Jan 20, 2015

All you need to do is to add required attribute and ng-model on the checkbox to make it necessary to check during form validation.

<li class="terms_checkbox">
   <input type="checkbox" 
       id="checkbox_terms" name="terms" ng-model="agreement" required />
   <label for="checkbox_terms"></label>
</li>

angular.module('app', []).controller('ctrl', function($scope) {

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <form name="form" novalidate>
    <ul>
      <li class="terms_checkbox">
        <input type="checkbox" id="checkbox_terms" name="terms" ng-model="agreement" required />
        <label for="checkbox_terms"></label>
      </li>
      <li class="accept">I have read and accept the terms and conditions</li>
      <li>
        <button ng-disabled="form.$invalid">Submit</button>
      </li>
    </ul>
  </form>
</div>