An Angular directive for Bootstrap 3 that intelligently applies the 'has-error' class to invalid form fields.
See the Bootstrap Form Validation Done Right in AngularJS blog post to read about the benefits of using this directive.
With Bower
bower install angular-bootstrap-show-errors
Manually
Copy the src/showErrors.js
or src/showErrors.min.js
file into your project.
- Include the
ui.bootstrap.showErrors
module in your Angular app
angular.module('yourApp', ['ui.bootstrap.showErrors']);
- Add the
show-errors
attribute on the div element that contains theform-group
class
<form name="userForm">
<div class="form-group" show-errors>
<input type="text" name="firstName" ng-model="firstName" ng-required />
</div>
</form>
By default this directive doesn't check the validity until the user tabs off the input element. However, there are times you want to show invalid form elements even if the user has not tabbed off. (e.g. before saving the form)
To force the validity check, broadcast the show-errors-check-validity
event.
<form name="userForm">
<div class="form-group" show-errors>
<input type="text" name="firstName" ng-model="firstName" ng-required />
</div>
<input type="submit" ng-click="save()" />
</form>
$scope.save = function() {
$scope.$broadcast('show-errors-check-validity');
if ($scope.userForm.$valid) {
// save the user
}
}
If you have functionality to reset your form, you can broadcast the 'show-errors-reset' event to remove any errors on the form elements.
<form name="userForm">
<div class="form-group" show-errors>
<input type="text" name="firstName" ng-model="firstName" ng-required />
</div>
<a href="#" ng-click="reset()">Reset</a>
</form>
$scope.reset = function() {
$scope.$broadcast('show-errors-reset');
}
It's also possible to let the user know when they have entered valid values by applying the 'show-success' class that Bootstrap provides. You can either apply this globally or on an element by element basis.
The following example shows how to show valid values on every input that uses the showErrors directive.
app = angular.module('yourApp', ['ui.bootstrap.showErrors']);
app.config(['showErrorsConfigProvider', function(showErrorsConfigProvider) {
showErrorsConfigProvider.showSuccess(true);
}]);
If you only want to show valid values on specific inputs, then you can pass in the { showSuccess: true }
option like the example below shows.
<form name="userForm">
<div class="form-group" show-errors="{ showSuccess: true }">
<input type="text" name="firstName" ng-model="firstName" ng-required />
</div>
</form>
Before you begin development, you will need to install the required node modules and bower components. To do so, open a terminal window in the project directory and run the following commands.
npm install
bower install
Run the following command from a terminal window to automatically compile and run the unit tests whenever you save changes to the source files.
grunt karma:unit:start watch