通用电子邮件验证器 [英] Generic email validator

查看:96
本文介绍了通用电子邮件验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a form where the user will enter his email. I'd like to validate email format client-side.

Angular 2中是否有任何通用的电子邮件验证程序?

Is there any generic email validator in Angular 2?

NB:类似于 AngularJS验证器./p>

NB: Something similar to AngularJS validator.

推荐答案

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

You can use Form Directives and Control to do this.

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';

然后您的GlobalValidator课:

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 或查看此github项目以获取

For more information about this, you can read this good article : https://medium.com/@daviddentoom/angular-2-form-validation-9b26f73fcb81#.jrdhqsnpg or see this github project for a working example.

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

(edit : that reg ex does not seem to check for a dot in the domain

我改用这个

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

这篇关于通用电子邮件验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆