Angular - 电子邮件验证不起作用

标签 angular

我正在使用 Angular-7 开发应用程序。我向 ts 添加了一个电子邮件验证器并从 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>

当我输入错误的电子邮件时,只要光标离开文本输入,就会显示此错误消息:

Email must be a valid email address

但是没有任何显示。

最佳答案

函数本身只返回 true or,但它不会判断验证是否正确。在模板驱动的表单中,需要通过 html 属性“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>

关于Angular - 电子邮件验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57883903/

相关文章:

html - Angular 4将值从html模板传递给组件中的方法

angular - 类型 'includes' 中缺少属性 'Observable<IProduct[]>'

angular - 在 chrome 开发工具中调试导入的 Angular 库

angular - 如何在 Angular2 中绑定(bind)原始 html

angular - 使用 Webpack 5 模块联合提供样式和 Assets

html - 不等柱形条(谷歌图表)

loops - Angular 2 - *ngFor : Is there a way to use an alternative end condition?

javascript - TS2322 : Type 'Promise<Hero | undefined>' is not assignable to type 'Promise<Hero>'

javascript - 动态调整 ag-Grid header 高度

Angular : How to check if some control exist in form or not