通用电子邮件验证器

Generic email validator

我想创建一个表单,用户将在其中输入他的电子邮件。我想在客户端验证电子邮件格式。

Angular2 中是否有任何通用电子邮件验证器?

注意:类似于 AngularJS validator

我想现在还没有电子邮件验证器,但添加自定义验证器非常容易。看到这个 demo 我使用了与 angular1 使用的相同的正则表达式。

function emailValidator(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 (!EMAIL_REGEXP.test(control.value)) {
    return {invalidEmail: true};
  }
}

您可以使用表单指令和控件来执行此操作。

export class TestComponent implements OnInit {
     myForm: ControlGroup;
     mailAddress: Control;

     constructor(private builder: FormBuilder) {
         this.mailAddress = new Control(
            "",
            Validators.compose([Validators.required, GlobalValidator.mailFormat])
        );
     }

     this.addPostForm = builder.group({
            mailAddress: this.mailAddress
     });
}

导入:

import { FormBuilder, Validators, Control, ControlGroup, FORM_DIRECTIVES } from 'angular2/common';

那么你的GlobalValidatorclass:

export class GlobalValidator {

    static mailFormat(control: Control): ValidationResult {

        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 { "incorrectMailFormat": true };
        }

        return null;
    }  
}

interface ValidationResult {
    [key: string]: boolean;
}

然后是你的 HTML:

<div class="form-group">
    <label for="mailAddress" class="req">Email</label>
    <input type="text" ngControl="mailAddress" />
    <div *ngIf="mailAddress.dirty && !mailAddress.valid" class="alert alert-danger">
        <p *ngIf="mailAddress.errors.required">mailAddressis required.</p>
        <p *ngIf="mailAddress.errors.incorrectMailFormat">Email format is invalid.</p>
    </div>
</div>

有关这方面的更多信息,您可以阅读这篇好文章:https://medium.com/@daviddentoom/angular-2-form-validation-9b26f73fcb81#.jrdhqsnpg or see this github project for a working example

(编辑:reg ex 似乎不检查域中的点

我改用这个

/^(([^<>()\[\]\.,;:\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,}))$/

cfr http://emailregex.com/

这是使用 RegEx 验证字段的另一种方法。可以给字段的keyUp事件绑定一个方法。

在你的组件中:

import {NgForm} from 'angular2/common';

//...

emailValidator(email:string): boolean {
    var 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,}))$/;

    if (!EMAIL_REGEXP.test(email)) {
        return false;
    }
    return true; 
}

在您的HTML(视图)中

<div class="form-group">
    <label>Email address</label>
    <input type="email" class="form-control" [(ngModel)]="user.email"
           placeholder="Email address" required ngControl="email"
           #email="ngForm"
           (keyup)="emailValidator(email.value) == false ? emailValid = false : emailValid = true">
    <div [hidden]="emailValid || email.pristine" class="alert alert-sm alert-danger">Email address is invalid</div>
</div>

另一个选项(必填字段 + 用户离开字段时验证)

<div class="form-group">
    <label for="registerEmail">Email address</label>
    <input type="email" class="form-control" [(ngModel)]="user.email"
           placeholder="Email address" required ngControl="email"
           #email="ngForm"
           (blur)="emailValidator(email.value) == true ? emailIsInvalid = false : emailIsInvalid = true">
    <div [hidden]="email.valid || email.pristine" class="alert alert-sm alert-danger">This field is required</div>
    <div [hidden]="!emailIsInvalid" class="alert alert-sm alert-danger">Email address is invalid</div>
</div>

此方法适用于任何验证,因此您可以更改 RegEx 并验证信用卡、日期、时间等...

您只能使用 html:

<md-input-container class="md-icon-float md-block" flex-gt-sm>
    <label>Email</label>
        <input md-input
            id="contact-email"
            type="text"
            ngControl="email"
            #email="ngForm"
            [(ngModel)]="contact.email"
            required
            pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$">

    <div class="md-errors-spacer" [hidden]="email.valid || email.untouched">
        <div class="md-char-counter" *ngIf="email.errors && email.errors.required">
            Email is required
        </div>
        <div class="md-char-counter" *ngIf="email.errors && email.errors.pattern">
            Email is invalid
        </div>
    </div>
</md-input-container>

angular4岁及以上:

根据 This 你可以使用 "email validator".

示例:

如果您使用模板驱动的表单:

<input type="email" name="email" email>
<input type="email" name="email" email="true">
<input type="email" name="email" [email]="true">

如果您使用模型驱动表单(又名 ReactiveFormsModule),请使用 Validators.email:

this.myForm = this.fb.group({
    firstName: ['', [<any>Validators.required]],
    email: ['', [<any>Validators.required, <any>Validators.email]],
});

旧答案:您可以使用 angular 2 FormGroup,

通过使用 validators.pattern 和这样的正则表达式:

 let emailRegex = '^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$';
 this.myForm = this.fb.group({
        firstName: ['', [<any>Validators.required]],
        email: ['', [<any>Validators.required,  <any>Validators.pattern(emailRegex) ]],
 });

另一种方法是使用自定义指令。我喜欢这种方法,因为它与其他 ng2 验证器更一致。

import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS } from '@angular/forms';
import { Validator, AbstractControl } from '@angular/forms';


@Directive({
    selector: '[validateEmail][formControlName], [validateEmail][formControl],[validateEmail][ngModel]',
    providers: [
        { provide: NG_VALIDATORS, useExisting: forwardRef(() => EmailValidator), multi: true }
    ]
})
export class EmailValidator implements Validator {

    constructor() {
    }

    validate(c: AbstractControl) {
        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;

        return EMAIL_REGEXP.test(c.value) ? null : {
            validateEmail: {
                valid: false
            }
        };


    }}

那么 html 中的用法是

<input class="form-control" 
               type="email"
               [(ngModel)]="user.emailAddress" 
               name="emailAddress" 
               placeholder="first.last@example.com"
               validateEmail

我想现在你可以在这里使用浏览器验证。电子邮件字段有很好的支持,您可以从 element.validity.valid 获得验证结果。你只需要通过 Angular 自定义验证器

详情见https://developer.mozilla.org/en-US/docs/Web/API/ValidityState and http://caniuse.com/#feat=input-email-tel-url

您还可以将 ng2-validation-manager 用于响应式表单,这使得验证匹配更容易:

this.form = new ValidationManager({
  'email'       : 'required|email',
  'password'    : 'required|rangeLength:8,50'
});

和视图:

<form [formGroup]="form.getForm()" (ngSubmit)="save()">

    <div class="form-group">
      <label>Email</label>
      <input type="text" class="form-control" formControlName="email">
      <div *ngIf="form.hasError('email')" class="alert alert-danger">
        {{form.getError('email')}}
      </div>
    </div>

    <div class="form-group">
      <label>Password</label>
      <input type="password" class="form-control" formControlName="password">
      <div *ngIf="form.hasError('password')" class="alert alert-danger">
        {{form.getError('password')}}
      </div>
    </div>
    <button type="submit" class="btn btn-success">Submit</button>
</form>

更新 Angular 4

ngOnInit() {
    this.user = new FormGroup({
        name: new FormGroup({
            firstName: new FormControl('',Validators.required),
            lastName: new FormControl('')
        }),
        age: new FormControl('',null,validate),
        email: new FormControl('',emailValidator),
    // ...
    });
}

验证者

export function emailValidator(control: AbstractControl):{[key: string]: boolean} {
    var 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,}))$/;
    if (control.value != "" && (control.value.length <= 5 || !EMAIL_REGEXP.test(control.value))) {
        return {invalid:true};
    }
    return null;
}

模板

<div class="row">
    <div class="col-md-12">
        <md-input-container>
            <input mdInput type="text" placeholder="Email" formControlName="email">
        </md-input-container>
    </div>
</div>
<div class="row">
    <div class="col-md-12">
        <span *ngIf="user.get('email').touched && !user.get('email').valid && !user.get('email').pristine">
            <small>Invalid email</small>
        </span>
    </div>
</div>

我正在使用: https://www.npmjs.com/package/ng2-validation

npm install ng2-validation --save ng2-validation

我不是在回答你的问题,但对于很多常见的场景,你可以找到一个已经实现的自定义验证器

您的例子: 电子邮件:['', [CustomValidators.email]]

此致,

您可以在没有表单的情况下使用内置的 Angular 表单验证器。我不确定这是否是个好习惯,但它确实有效。

const control = new FormControl('', Validators.email);
control.setValue(valueToCheck);
console.log(control.errors);

其他答案已经展示了如何在表格中使用它:

this.contactUsForm = this.formBuilder.group({
      firstName: new FormControl('', Validators.required),
      lastName: new FormControl('', Validators.required),          
      emailAddress: new FormControl('', [Validators.required, Validators.email]),
      message: new FormControl('', Validators.required)
    });