I\'m trying to make a custom Angular 2 form Validator
to check if a user exist on a data base.
This is the code of my custom form Validator
@Injectable()
export class EmailValidator {
constructor(private api:API) {}
/* static */ checkEmail(control: FormControl,): any {
return this.api.checkUser(control.value).then(response => {
response;
});
}
}
Add it to of @NgModule()
or @Component()
depending on what scope you want it to have
providers: [EmailValidator]
Inject it to the component where you want to use it
export class MyComponent {
constructor(private emailValidator:EmailValidator, fb:FormBuilder){}
this myForm = fb.group({
email: [], [this.emailValidator.checkEmail.bind(this.emailValidator)]
});
}