Angular 5 - form validation e-mail
Use pattern
attribute with a regular expression for email validation.
<div class="form-group">
<label for ="email">Email</label>
<input type="text" class="form-control" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" id="email"name="email" ngModel #emailref="ngModel">
<div *ngIf="emailref.errors &&(emailref.touched || emailref.dirty)" class ="alert alert-danger">
<div [hidden]="!emailref.errors?.pattern">
Invalid pattern
</div>
</div>
</div>
For Angular 8 versions there is inbuilt email validator available.
In component class variable
email= new FormControl('',[
Validators.required,
Validators.email
]);
In the component html
<input type="email" [formControl]="email" class="form-control" id="email" required>
<div *ngIf="email.invalid && (email.dirty || email.touched)"
class="alert alert-danger">
<div *ngIf="email.errors.required">
Email is required.
</div>
<div *ngIf="email.errors.email">
Please enter a valid email.
</div>
</div>
<div *ngIf="email.errors.email">
Please enter a valid email.
</div> //this is not work
<div *ngIf="email.errors.validateEmail">
Please enter valid email
</div > //use this
You can simply pass additional condition into the ngIf
directive to check if the current value of the input is empty string.
*ngIf="email.value !== '' && email.untouched && email.invalid"