8

How can I validate an email address to have an @ sign and a dot without pressing on a button, without a form. I would appreciate any help.

<mat-form-field class="example-full-width">
  <input matInput placeholder="Favorite food" value="Sushi">
</mat-form-field>
ryy77
  • 1,134
  • 5
  • 20
  • 36
  • https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript – AT82 Apr 18 '19 at 18:59

3 Answers3

17

You could use pattern and define a regex to validate email address,

<input matInput placeholder="Favorite food" [(ngModel)]="enterEmail" name="myEmail" pattern="[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}" required>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • 1
    do u know of a way to add a message to this? without having to declare it with a formcontrol tag – WtFudgE Jul 12 '19 at 12:21
3

I'm using Angular 8, and it has directive EmailValidator.

Use with ngModel like this:

<input type="email" name="email" ngModel email>
<input type="email" name="email" ngModel email="true">
<input type="email" name="email" ngModel [email]="true">
Robin Huy
  • 960
  • 7
  • 23
1

You can validate in this way as well

In your template(.html file):

<form
  [formGroup]="userForm"
  #formDirective="ngForm"
  (ngSubmit)="onFormSubmit()"
>
  <div class="form-control">
    <mat-form-field appearance="outline" class="form-field">
      <mat-label>Email Address</mat-label>
      <input
        type="text"
        matInput
        formControlName="email"
        class="form-input-field"
        pattern="[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}"
      />
      <mat-error *ngIf="userForm.get('email').hasError('required')"
        >Email is required</mat-error
      >
      <mat-error *ngIf="userForm.get('email').hasError('email')"
        >Please enter a valid email address
      </mat-error>
    </mat-form-field>
  </div>
</form>

In your component(.ts file):

userForm = new FormGroup({
  email: new FormControl('', [Validators.required, Validators.email]),
});
saberprashant
  • 388
  • 5
  • 15