A validator is created by implementing the Validator interface. This has a function validate that takes a FormGroup, returns null if the input is value or a key-value map of errors if it's invalid.
import { Directive } from '@angular/core';
import { FormGroup, Validator } from '@angular/forms';
@Directive({ selector: '[isItRad]' })
export class checkThingIsRadValidator implements Validator {
validate(control: FormGroup): {[key:string]: any} {
// if all valid => return null
// else => return { va
...
}
}
Validators are registered by registering against the NG_VALIDATORS token. The default value registered to this token is Angular's list of default validators.
Below you can see checkThingIsRadValidator is being registered against NG_VALIDATORS with useExisting. By itself this would overwrite all the default validators registered against NG_VALIDATORS. We solve this by adding multi: true which means checkThingIsRadValidator is appended to a list of things registered against the token.
...
import { ... NG_VALIDATORS } from '@angular/forms';
@Directive({
selector: '[isItRad]',
providers: [{
provide: NG_VALIDATORS,
useExisting: checkThingIsRadValidator,
multi: true
}]
})
export class checkThingIsRadValidator implements Validator {...}