Click here to Skip to main content
15,867,568 members
Articles / Web Development / HTML
Tip/Trick

AngularJS Validation Using Custom Directives

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
21 May 2015CPOL1 min read 24.1K   290   2  
Custom validation in AngularJS using custom directives
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:

Image 1

Using the Code

To use custom directives and any async functions, you must declare them in the input type fields. Notice firstname, userexists field.

Image 2

This allows you to register your own validation directives. Now we can do this in the controller to add logic to the directives.

C++
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:

C++
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:

HTML
<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.

HTML
<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

  • Version 1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Hello, I'm a developer in the Orlando area. I enjoy playing basketball, golf and learning about new technologies. I have a passion in the web development space and hope to learn more about how to creating useful apps and more importantly share my knowledge with the community.

I'm available for freelance work, specializing in web applications.
You can reach me at tonyjen0905@gmail.com

Comments and Discussions

 
-- There are no messages in this forum --