Building your own custom validator

Sometimes the default validators won't cover all the scenarios that you might have in your application. Luckily, it is quite easy to write your own custom validator.

A custom validator is just a function that needs to return an object with the error specified or null. Null means we don't have an error.

Starting to define such a function is easy:

import { AbstractControl, ValidatorFn } from '@angular/forms';

export function minValueValidator(compareToThisValue: number): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
const lessThan = parseInt( control.value ) < compareToThisValue;
return lessThan ? {'minValue'</span>: {value: control.value}} : null;
};
}

In this case, we are building a minValue validator. The outer function takes the parameter we will compare to. We return an inner function that tests the control's value to our compare value. If our condition is true we raise an error where we return an error structure { 'minValue' : {  value : control.value } }, or if it is false then we return null.

To use this new validator all we have to do is import it in our component file and type the following:

formBuilder.group({
age : [0, minValueValidator(18)]
})

And to show an error message in the template, if this error is raised, we just write this:

<div *ngIf="form.get('age').hasError('minValue')">
You must be at least 18
</div>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset