Ivan P Ivan P - 8 months ago 58
AngularJS Question

Reconcile Angular.js and Bootstrap form validation styling

I am using Angular with Bootstrap. Here is the code for reference:

<form name="newUserForm" ng-submit="add()" class="" novalidate>
<input type="text" class="input" ng-model="newUser.uname" placeholder="Twitter" ng-pattern="/^@[A-Za-z0-9_]{1,15}$/" required></td>
<button type="submit" ng-disabled="newUserForm.$invalid" class="btn btn-add btn-primary">Add</button>

Bootstrap has styles for invalid fields in the form of
input:invalid {.... }
; these kick in when the field is empty. Now I also have some pattern matching via Angular. This creates odd cases when ":invalid" is off, but ".ng-invalid" is on, which would require me to re-implement bootstrap CSS classes for the ".ng-invalid" class.

I see two options, but having trouble with both

  • Make Angular use some custom classname instead of "ng-valid" (I don't know how to do this).

  • Disable html5 validation (I thought that that's what "novalidate" attribute in the form tag should do, but couldn't get it work for some reason).

The Angular-Bootstrap directives out there don't cover 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}">
    <input type="text" name="name" ng-model="project.name" required>
    <span ng-show="myForm.name.$error.required" class="help-inline">

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