Form validation and custom validation directives are relatively easy with the changes in Angular 1.3. Try the sample plunk here.
Let’s look at the scenario where we need to confirm a new user’s password during registration. Registration is not so common in this day and age of federated identity, but is still a useful example and a frequent requirement.
We could put logic into a model to confirm a password, but it is probably better to separate the logic into a reusable directive. AngularJS already provides directives for the standard HTML validation attributes like required. All we need to do is follow a similar pattern.
1. Require the ngModel controller.
2. Add a method to the ngModel controller’s $validators object. Angular will invoke the function when the model value changes. The function returns a boolean, and a return value of false will set the corresponding ngModel’s $error property automatically.
The compare-to directive looks like the following:
var compareTo = function() { return { require: "ngModel", scope: { otherModelValue: "=compareTo" }, link: function(scope, element, attributes, ngModel) { ngModel.$validators.compareTo = function(modelValue) { return modelValue == scope.otherModelValue; }; scope.$watch("otherModelValue", function() { ngModel.$validate(); }); } }; }; module.directive("compareTo", compareTo);
You can use the directive inside of markup like so:
<input type="password" name="confirmPassword" ng-model="registration.user.confirmPassword" required compare-to="registration.user.password" /> <div ng-messages="registrationForm.confirmPassword.$error" ng-messages-include="messages.html"></div>
The ng-messages directives, also new in 1.3, makes it easy to provide common error messages for form inputs. You can also see them at work in the plunk.