Search code examples
angularformsvalidationemail-validation

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>

Solution

  • 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>