RSS

Writing a Custom Directive Compatible With Native Angular Form Validators

13 May

Directive is one of angular’s construct that gives great power where I think probably angular shines a lot than other similar libraries. They are great containers to encapsulate domain logic and to build domain specific language. Angular js has number of built in directives that supports form processing and other common tasks. What I am going to show is how to write custom validator plugin to angular js form validators that can be  hooked in to framework itself without writing extra validation code ourself.

Consider following simple form. (assume angular js is included)

<html ng-app="myApp">
<head>
  <title>My Application</title>
</head>
<body ng-controller="MainCtrl as ctrl">
  <form ng-submit="ctrl.submit()" name="myForm">
    <input type="text" ng-model="ctrl.page.name" required ng-minlength="4">
    <input type="text" ng-model="ctrl.page.description" required>
    <input type="submit" value="Submit" ng-disabled="myForm.$invalid">
  </form>
</body>
<!---Content With Angular JS Included-->.....

Above our imaginary “page” model will be validated out of the box nicely with angulars built in validation framework. In this case “page” name with required field, minium length of 4 characters and “page” description which is also required. Here I am disabling “Submit” button when the form is invalid.

 <input type="submit"
        value="Submit"
        ng-disabled="myForm.$invalid">

Notice that this acts as a validation group validator (ASP.NET developers are using same named control). If the any of form controls are invalid the property would be set to true hence submit button will be disabled. Let’s imagine we need to add another text box where we need to give page’s relative URL which must be started with “/” and until its validated form submission must be disabled. There are many ways of solving this but if we could hook our custom directive into angular validation framework then it would be not only very clean and robust but also you don’t need to write additional code to validate and decorate the UI.

(function(module) {
    function relativeUrl(){

       return {
            require:'ngModel',
            restrict:'A',
            link : function(element,scope, attributes, ngModel ){
                 ngModel.$validators.relativeUrl = function(modelValue) {
                     if(!modelValue || modelValue && modelValue.charAt(0) !=='/'){
                        return false;
                     }else{
                         return true;
                     }
                 }
            }
       };
    }
    module.directive('relativeUrl', relativeUrl);
})(
    angular.module('app')
);

In above we could inject “ngModel” built in angular controller we use quite often which allows to hook into angulars built in validation framework.

Page Submit Validator for Relative URLS Error Display

Page Submit Validator for Relative URLs Success

It is when all three input gets green that submit button will be enabled. You would observe that built in angular classes will be added up dynamically when according to the input text we type into the relative url textbox.

<input type="text" relative-url="" class="form-control ng-dirty ng-valid-parse ng-valid ng-valid-relative-url ng-touched" name="url" ng-model="relativeUrl" id="url">

This would be additional advantage when giving visual feedback to user when input is valid or invalid. I have added very basic input styling for that but styling you could do is far beyond this.

input.ng-valid{
            background-color: greenyellow;
            border: 1px solid darkgreen;

}
input.ng-invalid {
            border: 2px solid red;
}
Advertisements
 
Leave a comment

Posted by on May 13, 2015 in AngularJs

 

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: