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...
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime