As always I have included a live preview version here.
http://tonyjen.github.io/AngularJS-Validation-CustomDirectives/
Introduction
Previously, I talked about validation in AngularJS here:
I used pre-built validation directives and customize the error message. But what happens if you need a custom validation like checking for a certain keyword or doing calculation on a model to see if it is allowed.
This is where custom directives comes into play. Custom directives allow the developer to create his own keywords in addition to the prebuilt ones like text, number, email and other default ones.
Background
Here is a screen shot of a custom validation in action:
Using the Code
To use custom directives and any async
functions, you must declare them in the input type fields. Notice firstname, userexists field.
This allows you to register your own validation directives. Now we can do this in the controller to add logic to the directives.
app.directive("firstname", function () {
return {
restrict: "A",
require: "?ngModel",
link: function (scope, element, attributes, ngModel) {
ngModel.$validators.firstname = function (modelValue) {
if (modelValue == "Tony" || modelValue == "John") {
return true;
}
else return false;
};
}
};
});
Also, we can add async behavior to your directives as in the userexists
directive:
app.directive("userexists", function ($q, $timeout) {
var CheckUserExists = function (name) {
if (name == "Tony") {
return true;
}
else if (name == "John") {
return false;
}
else {
return false;
}
};
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attributes, ngModel) {
ngModel.$asyncValidators.userexists = function (modelValue) {
var defer = $q.defer();
$timeout(function () {
if (CheckUserExists(modelValue)) {
defer.resolve();
} else {
defer.reject();
}
}, 2000);
return defer.promise;
}
}
};
});
To make async
better for the user, you add a waiting dialog like this:
<div ng-if="tenantForm.FirstName.$pending">
Searching....
</div>
Putting It All Together
Now, we can add the error message to our application so when the validation fails, the correct error message will come up.
<div class="messages">
<div ng-message="required">Required</div>
<span ng-message="company">Company name must be ACME!</span>
<span ng-message="firstname">First name must be Tony or John!</span>
<span ng-message="userexists">The user John does not exists!</span>
</div>
Conclusion
Now with custom validation, you can do things like check if passwords match, searching for users in real time, add content in when users scroll pages and many others. Your application can be much more dynamic and more interactive.
I hope you enjoy this tip. I will post more on the back end in later articles.
Thanks!
History