When dealing with forms in Angular you can use the build-in validators like: required, minLength or maxLength, pattern… . Sooner or later you need a custom validator fulfilling a special validation.
Let’s have a form first:
We see a form which has a variable “f” representing the form with which we can ask for the current state. We also have an input control in which we can add a number - calories in this case.
I know that we could change the type of the input to number but in this post we want to check if whether the things the user typed are number or not.
So lets write a validator which exactly checks for that:
This validator is named “IsNumberValidator” and has a function with a FormControl as a parameter. After the imports we define a directive here and adding the selectors we want. The “providers” let us extend the build-in NG_VALIDATORS and add our new validator. The class implements the validator class with the “validate”-Method which takes a FormControl and returns null if everything is okay and not null if the validation fails.
Before we can use it in our form we have to include it in our module. I built a shared module which I include in my app.module.
and in our app.module:
We can use it in the form like
Here we add the validator to the input field of our form. It is only a directive so we can treat it this way like we did with every directive before.
So now the validator directive fires everytime a key is hit. We can now add a
... #calories="ngModel" ...
to the form and check if the variable we introduced is valid with
... calories.valid ...
But it would be nice to show specific error messages to the users and not only if the filed is valid or not. Combining the variable with the dirty-check and our validator-naming we can show the user messages exactly to what was going wrong in the form.