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.