加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2中的通用邮件验证器

发布时间:2020-12-17 08:18:45 所属栏目:安全 来源:网络整理
导读:我想创建一个用户将输入他的邮件的表单。 我想验证客户端的邮件格式。 Angular2中是否有任何通用的邮件验证器? 注意:与angularjs验证器类似的东西:https://docs.angularjs.org/api/ng/input/input%5Bemail%5D 您可以使用表单指令和控件来执行此操作。 exp
我想创建一个用户将输入他的邮件的表单。
我想验证客户端的邮件格式。
Angular2中是否有任何通用的邮件验证器?

注意:与angularjs验证器类似的东西:https://docs.angularjs.org/api/ng/input/input%5Bemail%5D

您可以使用表单指令和控件来执行此操作。
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项目为working example。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读