How to create a custom input validator with AngularJS

TL;DR: Scroll down for demo.

The following is a quick & dirty intro to how to create a custom $parser and add it to the ngModelController, which in more human translation could mean for example, adding a custom validator to the ng-model of the input.

Let’s assume we have a following requirement for our input, furthermore, we want our error messages to be usable/accessible with the new ng-messages:

  • exactly 6 characters in length
  • at least one number
  • one least one upper-case

We could approuch the first scenario with mix on ng-minlength & ng-maxlength, but for other two there are no such build-in AngularJS methods.

First of all we need to distinguish the different between $parsers & $formaters, both of which are available on our ngModelController.

  • formatters change how model values will appear in the view
  • parsers change how view values will be saved in the model

Coming back to our requirements, let’s assume we have a template which could look as per following:
What we need to do, is to create a custom directive which will tie to the ngModelController (to add our custom validator).

Important to notice in the below example is that we are requiring ngModelController, which than is passed in as a 4th param into our linking function:

OK, and the below in our linking function with newly added custom custom validator ($parser function), please see comments for explanation.
Big benefit of the above approach is that doing ctrl.$setValidity(‘validatorName’, [true/false]) will add an error (in case of validity set to false) the the form.strongSecret.$error.

This mean we can use ng-messages exactly the same as you would do with the AngularJS build-in validators. Please don’t forget to include ngMessages as a dependency of your AngularJS app angular.module(‘app’, [‘ngMessages’])

And finally, the whole thing in action:

More about NgModelController here: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
More about $parsers & $formaters here: http://stackoverflow.com/questions/22841225/angularjs-ngmodel-formatters-and-parsers

That is it, I really enjoy this approach with $parsers when creating addition/custom validators. Any suggestions much appreciated.

6 rules for mastering AngularJS

In no particular order of importance here are some rules/tips I follow when learning new programming language/framework. I am sure they can be applied to any language, but in this post I will focus primary on AngularJS.

AngularJS learning curve can be at times steep, very steep indeed- so early last year when I was trying to pick up the framework myself these tips/rules proved to be invaluable:

  1. When you are just starting make sure you learn from many simple examples, rather than from one that’s very complicated. Good example here would be series of tutorials from egghead.io – short & focused.
  2. It is important that you try to learn in time blocks and fairly frequently – e.g. 90 minutes every day.  Back when I first started with AngularJS, taking a two weeks break from using directives proved to be too long – I usually had to start from a blank page to “get back into the zone”. On another note, in my experience if you don’t work regularly on a project that seems very exiting at first you lose your interest & motivation.
  3. Always type in all of the code examples by hand, you may be tempted to just copy/paste, but typing in yourself will help you to get familiar with the syntax quickly (especially if there are plenty special characters such as “(“, “{” , “[” etc.. ).
  4. Always try to add something from yourself in every exercise you try,  maybe add extra parameters or functionality. For example, if the example you are working on means just submitting a form (just in browser memory), you can try extend this with LocalStorage or real database (MongoDB/Restangular/MongoLabs).
  5. Share what you have already learnt with the world, every tested and working example/exercise you have done can be of a great value to other people – share your code on GitHub, JSFiddle or write a blog post – this will help others following the same path as well may help you stay motivated & engaged.
  6. If you have a big resource on a language/framework you want to master – something like a book or a video course. I aways do my best to read/watch the whole thing. You don’t have to fully understand  what is going on – but if you get stuck on something that you know was covered in the book/video you will know exactly where to look for a solution. I highly recommend ng-book, but if you have a very strong willpower documentation will be good as well.

Here is a short list of other resources I’ve found very useful:

That would be all, if you have any tips please do share with us in the comments.