4

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.

1

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

Try this approach:

<input type="text" 
 class="form-control" 
 id="email" 
 placeholder="Email" 
 name="email" 
 [(ngModel)]="quoteModel.email" 
 #email="ngModel" 
 pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"
 [ngClass]="{'is-invalid' : email.invalid && ((email.dirty || email.touched) || quoteform.submitted)}"   
 required minlength="10"> <div class="md-errors-spacer" [hidden]="contactemail.valid || contactemail.untouched">

<div class="invalid-feedback" 
    [hidden]="email.valid || email.untouched">
    <div  *ngIf="email.errors && email.errors.required">
        Email is required
    </div>
    <div  *ngIf="email.errors && email.errors.pattern">
        Email is invalid
    </div>
</div>

1 Comment

that's for validation, doesn't answer his question and doesn't display the message he needs to have it display

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.