Reconcile Angular.js and Bootstrap form validation styling Reconcile Angular.js and Bootstrap form validation styling angularjs angularjs

Reconcile Angular.js and Bootstrap form validation styling


Use Bootstrap's "error" class for styling. You can write less code.

<form name="myForm">  <div class="control-group" ng-class="{error: myForm.name.$invalid}">    <label>Name</label>    <input type="text" name="name" ng-model="project.name" required>    <span ng-show="myForm.name.$error.required" class="help-inline">        Required</span>  </div></form>

EDIT:As other answers and comments point out - in Bootstrap 3 the class is now "has-error", not "error".


The classes have changed in Bootstrap 3:

<form class="form-horizontal" name="form" novalidate ng-submit="submit()" action="/login" method="post">  <div class="row" ng-class="{'has-error': form.email.$invalid, 'has-success': !form.email.$invalid}">    <label for="email" class="control-label">email:</label>    <div class="col">    <input type="email" id="email" placeholder="email" name="email" ng-model="email" required>    <p class="help-block error" ng-show="form.email.$dirty && form.email.$error.required">please enter your email</p>    <p class="help-block error" ng-show="form.email.$error.email">please enter a valid email</p>  ...

Note the quotes around 'has-error' and 'has-success': took a while to find that...


Another solution: Create directive which toggles has-error class according to a child input.

app.directive('bsHasError', [function() {  return {      restrict: "A",      link: function(scope, element, attrs, ctrl) {          var input = element.find('input[ng-model]');           if (input.length) {              scope.$watch(function() {                  return input.hasClass('ng-invalid');              }, function(isInvalid) {                  element.toggleClass('has-error', isInvalid);              });          }      }  };}]);

and then simple use it in template

<div class="form-group" bs-has-error>    <input class="form-control" ng-model="foo" ng-pattern="/.../"/></div>