Friday, August 23, 2013

Using AngularJS with Bootstrap Form Validation

If you are using AngularJS with Bootstrap (formerly Twitter Bootstrap), you will want to use AngularJS's form validation with Bootstrap's form classes. This can be surprisingly tricky and requires careful use of AngularJS's ngClass directive.

This is best illustrated with sample markup. It's extracted from a project that I'm working on:


The general idea behind this is that you need to set Bootstrap's 'has-error' class when loginForm's email field is invalid. Simple enough, right?

AngularJS introduces two issues that are present in the latest unstable version (1.2.0rc1). They could be in previous versions, but I didn't check.
  1. You must have quote marks around the name of the 'has-error' class in the ng-class expression.
  2. The input must be bound to the model by using AngularJS's ngModel directive
If you just put ng-class='{has-error: loginForm.email.$invalid}' your JS will crash within AngularJS because it's an invalid expression.

I have little idea why data binding is required. I suspect that AngularJS requires it because it expects you to use the field's contents somewhere else in your app.

No comments:

Post a Comment