我想创建一个表单,用户将在其中输入他的电子邮件。我想在客户端验证电子邮件格式。
Angular 2 中是否有任何通用的电子邮件验证器?
注意:类似于AngularJS 验证器的东西。
您只能使用 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>
对于角度 4 及以上:
根据这你可以使用“电子邮件验证器”。
例子:
如果您使用模板驱动的表单:
<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) ]],
});
您可以使用表单指令和控件来执行此操作。
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 项目以获取工作示例。
(编辑: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,}))$/
这是使用 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 并验证信用卡、日期、时间等...
另一种方法是使用自定义指令。我喜欢这种方法,因为它与其他 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
我想刚才没有电子邮件验证器,但添加自定义验证器很容易。请参阅此演示,我使用了与 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};
}
}
您还可以将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>
我认为现在你可以在这里使用浏览器验证。电子邮件字段有不错的支持,您可以从element.validity.valid
. 你只需要通过 Angular 自定义验证器传递它
有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/ValidityState和http://caniuse.com/#feat=input-email-tel-url
我正在使用: 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)
});