Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Email validation is not working

Tags:

angular

I am using Angular-7 to develop an application. I added an email validator to the ts and call it from the HTML

client-quote-landing.ts

import { Component, OnInit, Inject, LOCALE_ID, TemplateRef } from '@angular/core';

import { Router, ActivatedRoute } from '@angular/router';
import { ClientQuoteService } from '../../../../shared/services/client-quote.service';
import { first } from 'rxjs/operators';
import { ToastrService } from 'ngx-toastr';
import { formatDate } from '@angular/common';
import { Validators, FormBuilder, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-client-quote-landing',
  templateUrl: './client-quote-landing.component.html',
  styleUrls: ['./client-quote-landing.component.scss']
})
export class ClientQuoteLandingComponent implements OnInit {

  quoteModel: any = {};
  formattedAddress = '';

  constructor(
    private clientQuoteService: ClientQuoteService, private toastr: ToastrService,
    private router: Router,
    @Inject(LOCALE_ID) private locale: string,
    private route: ActivatedRoute
  ) {

  }

  ngOnInit() {
    window.dispatchEvent(new Event('load'));
    window.dispatchEvent(new Event('resize'));

    // document.body.className = 'skin-blue sidebar-mini';
  }


   onCreateQuote(quoteform: any) {
      if (!quoteform.valid) { // return false if form not valid
        return false;
    }

      this.clientQuoteService.createClientQuote(this.quoteModel)
      .pipe(first())
      .subscribe(
        response => {
          if (!response['success']) {
            this.toastr.error(response['message']);
            return false;
          }
          this.toastr.success(response['message']);
          quoteform.reset();
          quoteform.resetForm();
          this.router.navigate(['landing']);
        },
        error => {
          this.toastr.error(error);
        }
      );
   }


emailOnly(event): boolean {
  const charCode = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$';

  return true;
}



}

client-quote-landing.html

<div class="col-xs-6">
 <label for="email">Email</label>
 <div class="input-group">
 <div class="input-group-addon">
   <i class="fa fa-envelope"></i>
 </div>
 <input type="text" 
     (keypress)="emailOnly($event)" 
     class="form-control" 
     id="email" 
     placeholder="Email" 
     name="email" 
     [(ngModel)]="quoteModel.email" 
     #email="ngModel" 
     [ngClass]="{'is-invalid' : email.invalid && ((email.dirty || email.touched) || quoteform.submitted)}"   
     required minlength="10">                         
 </div>
 <div 
    class="form-feedback" 
    *ngIf="email.invalid && ((email.dirty || email.touched) || quoteform.submitted)" 
    class="invalid-feedback">
    <div style="color:red;" 
         *ngIf="email.errors?.required" 
         class="alert alert-danger">
        Email is required.
    </div>
    <div style="color:red;" 
        *ngIf="email.errors?.email">
        Email must be a valid email address
    </div>
 </div>   
 </div>

When I type a wrong email, as soon as the cursor leaves the text input, this error message should be displayed:

Email must be a valid email address

But nothing is displayed.

like image 817
midowu Avatar asked Oct 29 '25 15:10

midowu


1 Answers

The function in itself returns only true or, but it does not tell if validation is correct. In a template driven form the validation needs to be made by the html attribute "pattern".

<div class="form-group">
          <label for="uname1">Email</label>
          <input
          type="email"
          [(ngModel)]="registerUserData.email"
          #email="ngModel"
          name="email"
            pattern="[^ @]*@[^ @]*.[^ .]"
            class="form-control rounded-0"
            required
            [ngClass]="{

            'is-invalid': email.invalid && ( email.dirty || email.touched ),
            'is-valid': email.valid && ( email.dirty || email.touched )

          }">
          <div class="invalid-feedback" *ngIf="email.invalid && email.touched">

            <p *ngIf="email.errors.pattern || email.touched ">Email required must contaion a @ and .(dot)</p>
          </div>
        </div>
like image 192
Grei Muka Avatar answered Oct 31 '25 05:10

Grei Muka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!