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?
The <input type="email"> defines a field for an e-mail address. The input value is automatically validated to ensure it is a properly formatted e-mail address. To define an e-mail field that allows multiple e-mail addresses, add the "multiple" attribute. Tip: Always add the <label> tag for best accessibility practices!
2 Methods of email validation in Angular Built-in validator: Angular features several built-in email validators, including EmailValidator. You can use them to verify the user-provided email addresses. Pattern validation: Pattern validation enables you to specify a regular expression (regex).
ValidatorFnlinkA function that receives a control and synchronously returns a map of validation errors if present, otherwise null. interface ValidatorFn { (control: AbstractControl<any, any>): ValidationErrors | null }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With