Reactive Forms How to show one error message at a time?

Viewed 607

Im using Angular 7 and have created a Reactive Form. The input field email has two validators set on it see below:

email: ['', [Validators.email, Validators.pattern('^[\\w._]+@company(.com|.go|.jet)')]],

Both validators have 2 errors messages in the template:

<label for="email" class="error-msg" *ngIf="authForm.get('email').hasError('email')  && hideFocus">Your email is invalid</label>
<label for="email" class="error-msg" *ngIf="authForm.get('email').hasError('pattern')  && hideFocus">Only emails ending with .com .go and .jet are allowed</label>

When the user types in the input field both errors are displayed at the same time.

How can I display one error message at a time? Is it possible?

2 Answers

If both errors are generated (because the input does not satisfy either of the validation rules), you could implement an ngIf-else switch to display whichever error you want first. An example of this can be found here.

A logical operator will be helpful here. You can check if the one error is not valid and another is valid. Theory might be little bit confusing, here is the example below:

<label for="email" class="error-msg" *ngIf="authForm.get('email').hasError('email')  && hideFocus">Your email is invalid</label>
<label for="email" class="error-msg" *ngIf="!authForm.get('email').hasError('email') && authForm.get('email').hasError('pattern')  && hideFocus">Only emails ending with .com .go and .jet are allowed</label>

I haven't used reactive forms yet so you need to work with above syntax properly, I use ngForm. The simple logic behind this is to check if the one error is not valid and another is valid which will show one error at a time.

An edit with correct syntax will be highly appreciated.

Related