i want to solve this problem: Angular 5 - template driven form
An input-field has type email. Example:
<input type="email" [(ngModel)]="model.email" #email="ngModel" email />
I want to validate this field. But it should not be a required field. The validation should only start, if it isn't empty. If the field is empty, everthing is fine. Otherwise an error message should be displayed until the e-mail adress is correct.
This is not realy working:
*ngIf="email.untouched && email.invalid"
So, how can i validate the email field? I miss a status like "not empty".
Any hint?
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>