Menu

Tag Archives: custom validation

Angular JS having very strong support for form validation. It’s having builtin $error object,predefined CSS classes and patterns that makes the form validation much easier. Still there are plenty of cases where we can not use angularjs default validation.Its off course not possible to cover all the cases.

So we can write up our own custom directives for adding custom validation to our application.What we really want to do is to build a directive that will require ngModel(require: ‘ngModel’). Requiring ngModel will pass the ngModelController into the linking function as the fourth argument. The ngModel controller has a lot of handy functions on it, in particular there is $setValidity, which allows us to set the state of a model field has $valid or $invalid as well as set an $error flag.
The ng-model directive provides two arrays of functions to which the custom validation logic can be hooked:i.e

$parsers

$formatters

Usage of both of these arrays looks similar, but they are invoked under different conditions.

$parsers:

Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. Each function is called,
in turn, passing the value through to the next. The last return value is used to populate the model. Used to sanitize /convert the value as well as validation. For validation, the parsers should update the validity state using $setValidity(), and return undefined for invalid values.

In most of the cases, $parsers is the right option to handle the logic of custom validation. Functions added to $parsers are called as soon as the value in the form input is modified by the user.

$formatters:

Array of functions to execute, as a pipeline, whenever the model value changes. Each function is called, in turn, passing the value through to the next. Used to format / convert values for display in the control and validation.
Formatters are invoked when the model is modified in the code. They are not invoked if the value is modified in the textbox. $formatters are useful when there is a possibility of the value getting modified from the code.

Example:

Suppose we want to validate our username. It must be alphanumeric only.

Though we can achieve the same kind of validation easily using ng-pattern, I have shown this example just for the demo purpose to show how $parser and $formatter works. Here is the PLUNK.