I have a concept where the user can submit a form and if the email is already registered, an error triggered by the API should display. I am using reactive forms with FormBuilder and trying to implement the validator in the subscribe error handler.
Constructor :
this.email = fb.control('', [Validators.required, Validators.pattern(/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/), SignupComponent.alreadyExist()]);
this.username = fb.control('', [Validators.required, Validators.pattern(/^([A-ZÀ-ÿa-z0-9]{2,})+(?:[ _-][A-ZÀ-ÿa-z0-9]+)*$/)]);
this.userRegisterForm = fb.group({
email: this.email,
username: this.username
});
Custom alreadyExist() validator :
static alreadyExist(alreadyExist: boolean = false): any {
return (control: FormControl): { [s: string]: boolean } => {
if(alreadyExist) {
return { emailAlreadyExist: true }
}
}
}
onSubmit() :
this.user.create(newUser)
.subscribe(
data => {
this.router.navigate(['signin']);
},
error => {
if(error.status === 401) {
// ATTEMPTING TO USE THE VALIDATOR HERE BY SETTING : FALSE
SignupComponent.alreadyExist(true);
}
this.loading = false;
});
Although it seems like the validator is being called, the anonymous method inside it is not activated. Is this not a recommended approach? Any suggestions would be greatly appreciated. Thank you.