Can anyone please guide what is the proper way to implement custom validator for Reactive form if we are not using template driven forms at all?
I have gone through
https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html
and
https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#custom-validation
Both in the end create a directive, is it necessary? or can we do it without creating a directive?
I tried this:
//my-app.module.ts
export interface ValidationResult {
[key: string]: boolean;
}
function personName(control: FormControl): ValidationResult {
if (!control.value) {
return null;
}
var valid = /^[a-zA-Z. ]*$/.test(control.value);
if (valid) {
return null;
}
return { "pattern": true };
}
@NgModule({
imports: [
CommonModule,
ReactiveFormsModule
],
declarations: [
MyComponent
],
exports: [
],
providers: [{ provide: NG_VALIDATORS, useExisting: personName, multi: true }]
})
export class MyModule { }
But when I apply personName validator to my reactive form, and test it in browser I get below error in console:
ERROR Error: Uncaught (in promise): Error: No provider for personName!