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

Angular 2中有通用的邮箱验证程序吗?

注:类似于AngularJS validator.

推荐答案

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

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.

(编辑: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/

Typescript相关问答推荐

带脉轮UI的TypScript支持StyleProps的正确方法是什么?

如何将函数类型应用到生成器?

Angular 17 -如何在for循环内创建一些加载?

React router 6.22.3不只是在生产模式下显示,为什么?

如何在typescript中设置对象分配时的键类型和值类型

Express Yup显示所有字段的所有错误

角效用函数的类型推断

React Typescript项目问题有Redux-Toolkit userSlice角色问题

部分更新类型的类型相等

为什么在leetcode问题的测试用例中,即使我确实得到了比预期更好的解决方案,这段代码也失败了?

防止重复使用 Select 器重新渲染

如何缩小函数的返回类型?

带投掷的收窄类型

Angular 16将独立组件作为对话框加载,而不进行布线或预加载

创建一个TypeScrip对象并基于来自输入对象的约束定义其类型

如何正确地将元组表格输入到对象数组实用函数(如ZIP)中,避免在TypeScrip 5.2.2中合并所有值

使用强制转换编写打字函数的惯用方法

如何在TypeScript中将元组与泛型一起使用?

什么';是并类型A|B的点,其中B是A的子类?

对象只能使用 Typescript 中另一个对象的键