Asma Alghamdi
Asma Alghamdi

Reputation: 81

validate email pattern in angular

I'm trying to prevent user to submit the form if he types invalid email format, my issue is he can type text and submittd the form successfuly even it present error massege but still submit the form, I'm not using formGroup my html code:

<div class="form-group">
   <label for="fromEmail">From Email</label>
   <input type="email"  required name="fromEmail" #fromEmail="ngModel" id="fromEmail" 
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" [(ngModel)]="currentForm.subscribers.subscriber[0].fromEmail" class="form-control" required minlength="1" maxlength="100" />
   <div class="color"  *ngIf="fromEmail.errors.required">Email is required</div>
   <div *ngIf="fromEmail.errors &&(fromEmail.touched || fromEmail.dirty)" class ="alert alert-danger">
      <div [hidden]="!fromEmail.errors?.pattern">
         Invalid pattern
      </div>
   </div>
</div>

Upvotes: 1

Views: 587

Answers (2)

Rodolfo Spier
Rodolfo Spier

Reputation: 188

I would normally use a reactive form for this, as it already has a standard e-mail validation. But in your case what I would suggest is:

<div class="form-group">
   <label for="fromEmail">From Email</label>
   <input type="text" required name="fromEmail" ngModel #fromEmail="ngModel" id="fromEmail" 
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" class="form-control" minlength="1" maxlength="100" />
   <div class="color"  *ngIf="fromEmail.errors.required">Email is required</div>
   <div *ngIf="fromEmail.errors &&(fromEmail.touched || fromEmail.dirty)" class ="alert alert-danger">
      <div [hidden]="!fromEmail.errors?.pattern">
         Invalid pattern
      </div>
   </div>
</div>

Upvotes: 0

saad shafiq
saad shafiq

Reputation: 161

In HTML call the method and pass the value entered in it

<input value="{{ emailValidation(value)}}" type="text">
<p *ngIf ="!emailValidation()">ERROR BOX<p>

In .TS file make a custom method and it will validate the email, keep it boolean so it can return true and false based on the email

   emailValidation(value) {
       // logic
     return true;
      }

On submit

   <button  (click)="save()" [disabled]="!emailValidation()">Submit</button>

p.s It is not the best approach, and it is a pseudo-code but you will get the idea.

Upvotes: 1

Related Questions