Creating and integrating custom form validators
With the addition of the validator pipeline, AngularJS's form validation is now highly extensible and straightforward to expand.
How to do it…
Formerly, custom form validation required messiness involving parsers and formatters; this is no longer the case. Custom validation can now be encapsulated cleanly within a directive.
Synchronous validation
The
ngModel
directive now exposes the $validators
property, which allows you to directly tap into its form validation.
The following directive definition is an example of a custom validator that ensures that a model value is not Packers
:
(app.js) angular.module('myApp', []) .directive('validateFavoriteTeam', function() { return { require : 'ngModel', link : function(scope, element, attrs, ngModel) { // define custom validator "favoriteTeam" ngModel.$validators.favoriteTeam = function(team) { // check string inequivalency...