Angular 5 - form validation e-mail

2019-02-13 10:04发布

问题:

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?

回答1:

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"



回答2:

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 ="aler alert-danger">
           <div [hidden]="!emailref.errors?.pattern">
             Invalid pattern
           </div> 
          </div> 
    </div>