Reputation: 39
I'm trying to validate login form and check if email is valid (I'd like to block some kind of 10minutes mails) so alongside with mat-errors
for invalid email pattern I wanna display an error that email is not valid or real.
I have an api for that so I'm sending email to the server and it returns me response true of false an I'm trying to display another mat-error
instead of default one but got stuck in that. I've read about ErrorStateMatchers
but I didn't find how to integrate my api service inside. Could you help me or give some hints please.
Here is my html template:
<mat-form-field class="form-input">
<div class="input-wrapper">
<span class="material-icons">person</span>
<input matInput class="input" type="email" name="email" (blur)="validateEmail()" formControlName="email"
[readonly]="disabledForm">
</div>
<mat-error class="input-error" *ngIf="loginForm.get('email').touched && formErrorsText['email']" translate>
{{ formErrorsText['email'] }}
</mat-error>
<mat-error class="input-error" *ngIf="!(validEmail$ | async)">
{{ 'AUTH.LOGIN.INVALID_EMAIL'| translate }}
</mat-error>
</mat-form-field>
Basically if I replace
<mat-error class="input-error" *ngIf="!(validEmail$ | async)">
{{ 'AUTH.LOGIN.INVALID_EMAIL'| translate }}
</mat-error>
with
<div class="input-error" *ngIf="!(validEmail$ | async)">
{{ 'AUTH.LOGIN.INVALID_EMAIL'| translate }}
</div>
it's been displayed, but I wanna understand why I can't use mat-error
.
Here is my apiService
validateEmail(): void {
if (this.loginForm.valid) {
this.validEmail$ = this.emailValidationService.checkEmail(this.loginForm.get('email').value)
.pipe(map(response => !response?.trust_rate || response?.trust_rate < 50));
}
}
Upvotes: 0
Views: 457
Reputation: 2131
In your validateEmail()
method, you could do something like
validateEmail(): void {
if (this.loginForm.valid) {
this.emailValidationService.checkEmail(this.loginForm.get('email').value)
.subscribe(response => {
//Apply your checks, if invalid then
this.loginForm.get('email').setErrors({serverError: 'Your Error'});
});
And in your template,
<mat-error *ngIf="form.get('email').errors?.serverError">
{{ form.get('email').errors?.serverError }}
</mat-error>
mat-error seems to be bound to the status of the <form-field>
it is enclosed in and hence setting an error on the form field correctly marks the field dirty.
Upvotes: 1