【问题标题】:Angular 2 Email ValidatorAngular 2 电子邮件验证器
【发布时间】:2021-07-19 02:08:59
【问题描述】:

我的简单电子邮件验证器出现问题。控制我的 html 的 .ts 页面具有以下代码:

import {EmailValidator} from  '../../validators/email';
@Component({
  templateUrl: 'build/pages/auth-signup/auth-signup.html',
})

export class AuthSignupPage {
  constructor(private formBuilder: FormBuilder) {
     this.slideOneForm = new FormGroup({
          firstName: new FormControl('', [
              Validators.maxLength(30), 
              Validators.pattern('[a-zA-Z ]*'),
              Validators.required
              ]),
          lastName: new FormControl('', [
              Validators.maxLength(30), 
              Validators.pattern('[a-zA-Z ]*'), 
              Validators.required]),
          email: new FormControl('', [
              Validators.maxLength(30), 
              EmailValidator.isValidMailFormat, 
              Validators.required]),
          password: new FormControl('', [
              Validators.maxLength(30), 
              Validators.required]),
          confirmPassword: new FormControl('', [
              Validators.maxLength(30), 
              Validators.required])
      });
  }
}

我的 HTML 代码是:

  <ion-item>
    <ion-label floating>Email (this will be your login/username)</ion-label>
    <ion-input #email (change)="elementChanged(email)" formControlName="email" type="email" [class.invalid]="!slideOneForm.controls.email.valid && (emailChanged || submitAttempt)"></ion-input>
  </ion-item>

最后,保存验证器的 email.ts 如下所示:

import {Control} from '@angular/common';


export class EmailValidator {

   static isValidMailFormat(control: Control){
        var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;

        if (control.value != "" && (control.value.length <= 5 || !EMAIL_REGEXP.test(control.value))) {
            return { "Please provide a valid email": true };
        }

        return null;
    }

}

在我的主 .ts 文件中引用此验证器时,我一直出错。例如,将鼠标悬停在“EmailValidator.isValidMailFormat”上时出现此错误

[ts] 
Argument of type '(ValidatorFn | ((control: Control) => { "Please provide a valid email": boolean; }))[]' is not assignable to parameter of type 'ValidatorFn | ValidatorFn[]'.
  Type '(ValidatorFn | ((control: Control) => { "Please provide a valid email": boolean; }))[]' is not assignable to type 'ValidatorFn[]'.
    Type 'ValidatorFn | ((control: Control) => { "Please provide a valid email": boolean; })' is not assignable to type 'ValidatorFn'.
      Type '(control: Control) => { "Please provide a valid email": boolean; }' is not assignable to type 'ValidatorFn'.
        Types of parameters 'control' and 'c' are incompatible.
          Type 'AbstractControl' is not assignable to type 'Control'.
            Property 'updateValue' is missing in type 'AbstractControl'.
import EmailValidator

我做错了什么?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    现在更好的是,Angular 4 内置了电子邮件验证器 https://github.com/angular/angular/blob/master/CHANGELOG.md#features-6 https://github.com/angular/angular/pull/13709

    只需将 email 添加到标签即可。例如,

      <form #f="ngForm">
        <input type="email" ngModel name="email" required email>
        <button [disabled]="!f.valid">Submit</button>
        <p>Form State: {{f.valid?'VALID':'INVALID'}}</p>
      </form>
    

    【讨论】:

    • 但仍然需要更多验证,因为我可以在没有“.com”的情况下编写 test@test,这不是有效的电子邮件
    • user@host 是有效的电子邮件。主机部分不需要有效的 TLD。当然,您的邮件路由器只会尝试在您的本地域上进行路由。
    • 不幸的是,这个电子邮件验证器将 john.doe@gmail 验证为 true,即使它缺少 .com 部分。
    • 这些 cmets 很好地说明了为什么人们不应该编写自己的电子邮件验证器——他们最终会为他们“认为”有效的东西编写验证器......
    【解决方案2】:

    通过在我的 validator.ts 的第一行将导入的类从 Control 更改为 FormControl 解决了这个问题:

    import {FormControl} from '@angular/forms';
    
    
    export class EmailValidator {
    
       static isValidMailFormat(control: FormControl){
            let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    
            if (control.value != "" && (control.value.length <= 5 || !EMAIL_REGEXP.test(control.value))) {
                return { "Please provide a valid email": true };
            }
    
            return null;
        }
    
    }
    

    【讨论】:

    • 我建议将control.value != "" 更改为control.value,因为在某些情况下它可能会产生未捕获的异常。
    【解决方案3】:
    <input type="email" pattern="^[^\s@]+@[^\s@]+\.[^\s@]{2,}$">
    

    pattern 属性可用于自定义验证

    【讨论】:

    • 真的很简单。 pattern 属性让您可以编写自己的正则表达式模式来验证 fx
    【解决方案4】:

    Angular 9+ 和 Ionic 5+

    默认 Angular 电子邮件验证器对于我的用例来说是不够的。所以我用了这个:

    form.ts

         this.form = this.formBuilder.group({
             
              email: ['', Validators.compose([Validators.required, 
                          Validators.pattern(RegularExpressionConstant.EMAIL)])],
              });
    

    正则表达式.constant.ts

    export class RegularExpressionConstant {
        static EMAIL: RegExp = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    }
    

    【讨论】:

    • 这对我有用,谢谢。下面的代码:email: ['', Validators.compose([Validators.required,Validators.email])]
    【解决方案5】:

    只需使用Validators.pattern('^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$')

    .ts 代码:

    import { Component } from '@angular/core';
    import { NavController} from 'ionic-angular';
    import { Observable } from 'rxjs/Observable';
    import { UserDetails } from '../../app/Model/UserDetails';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    @Component({
      selector: 'page-login',
      templateUrl: 'login.html'  
    })
    export class LoginPage {
    logForm: FormGroup;
      email: string;
      constructor(public navCtrl: NavController,public formBuilder: FormBuilder) {
        this.logForm = formBuilder.group({
          email: ['', Validators.compose([Validators.required, Validators.pattern('^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$'), Validators.minLength(1)])],
          password: ['', Validators.compose([Validators.required, Validators.minLength(8)])],
    
        });
      }
    
    
      onSubmit(value: any): void {
        if (this.logForm.valid) {
          //window.localStorage.setItem('username', value.username);
          //window.localStorage.setItem('password', value.password);    
        }
      }
    
    
    }
    

    HTML 代码:

        <form [formGroup]="logForm" (ngSubmit)="onSubmit(logForm.value)">
          <div class="login-user-input">
    
            <ion-item>
              <ion-label class="label"  fixed>Email</ion-label>
              <ion-input type="text" formControlName="email" [(ngModel)]="user.Email" ></ion-input>
            </ion-item>
            <ion-item *ngIf="logForm.controls.email.hasError('pattern') && logForm.controls.email.touched">
              <p>Please enter valid Email</p>
            </ion-item>
            <ion-item>
              <ion-label class="label"  fixed>Password</ion-label>
              <ion-input type="password" formControlName="password" maxlength="8" [(ngModel)]="user.password"></ion-input>
            </ion-item>
            <ion-item *ngIf="logForm.controls.password.hasError('minLength') && logForm.controls.password.touched">
              <p>Please enter valid Password</p>
            </ion-item>
          </div>
          <div>
            <button text-center class="customersubmitbtn" [disabled]="!logForm.valid" color="primary" >Login</button>
          </div>
        </form>
    

    【讨论】:

      【解决方案6】:
         // SIMPLE SNIPPIT CODE
          
              this.myReactiveForm = new FormGroup({
                    id: new FormControl(''),
                    fullName: new FormControl('',Validators.compose([Validators.required,Validators.minLength(2),Validators.pattern('^[a-zA-Z][a-zA-Z0-9.,$;]+$')])),
                    email: new FormControl("", Validators.compose([Validators.pattern(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)])),
                    mobile: new FormControl('',Validators.compose([Validators.required,Validators.pattern("^((\\+91-?)|0)?[0-9]{10}$")])),
                    address: new FormControl(''),
                  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-03
        • 2016-10-23
        • 2014-02-17
        • 2013-10-28
        • 2020-06-18
        • 1970-01-01
        • 2022-08-13
        • 2019-07-02
        相关资源
        最近更新 更多