Reputation: 451
I'm doing reactive form validation I have found out that this *ngIf has a bug on checking a valid email pattern. When we write an invalid email and click outside of the input *ngIf for pattern check will always return even if the input is valid. Please check the demo video.
Here's the Video of the bug please check
.html
<form name="form" [formGroup]="form">
<div class="form-group" [ngClass]="{'has-danger': form.get('email').touched && form.get('email').invalid, 'has-success': form.get('email').valid}">
<label for="email">Email Address</label>
<input type="email" class="form-control" name="email" formControlName="email" id="email" placeholder="Email Address">
<div *ngIf="form.get('email').touched && form.get('email').errors.required" class="form-control-feedback">This field is required!</div>
<div *ngIf="form.get('email').errors?.pattern" class="form-control-feedback">Email is Invalid!</div>
</div>
</form>
.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-career-page',
templateUrl: './career-page.component.html',
styleUrls: ['./career-page.component.css']
})
export class CareerPageComponent implements OnInit {
constructor() { }
form = new FormGroup({
firstName: new FormControl('', Validators.required),
lastName: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,3}$')]),
})
ngOnInit(): void {
}
}
Upvotes: 0
Views: 2816
Reputation: 927
I think this situation is happening cause the div messages are not nested. Once the user clicks outside, form.get('email').errors will become null, so therefore the the above scenario occurs..
The *ngIf on the first div should have a condition such that only upon touch or some condition like that and only then should it display the nested div messages like 'field is required' or 'Enter valid email'...
Please try this code to verify:
<form name="form" [formGroup]="form">
<div class="form-group" [ngClass]="{'has-danger': form.get('email').touched && form.get('email').invalid, 'has-success': form.get('email').valid}">
<label for="email">Email Address</label>
<input type="email" class="form-control" name="email" formControlName="email" id="email" placeholder="Email Address">
<div *ngIf="form.get('email').invalid && (form.get('email').dirty || form.get('email').touched)">
<div *ngIf="form.get('email').errors.required" class="form-control-feedback">This field is required!</div>
<div *ngIf="form.get('email').errors?.pattern" class="form-control-feedback">Email is Invalid!</div>
</div>
</div></form>
Upvotes: 2