答案 0 :(得分:76)
你只能使用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>
答案 1 :(得分:62)
对于角度4及以上:
根据 This ,您可以使用“电子邮件验证工具”。
示例:
如果您使用模板驱动的表单:
<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和regex:
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) ]],
});
答案 2 :(得分:44)
您可以使用表单指令和控件来执行此操作。
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,}))$/
答案 3 :(得分:6)
以下是使用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并验证信用卡,日期,时间等...
答案 4 :(得分:5)
另一种方法是使用自定义指令。我喜欢这种方法,因为它与其他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
答案 5 :(得分:3)
答案 6 :(得分:1)
此外,您可以将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>
答案 7 :(得分:1)
更新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>
答案 8 :(得分:0)
我认为现在你可以在这里使用浏览器验证。电子邮件字段提供了不错的支持,您可以从element.validity.valid
获得验证结果。您只需要通过Angular自定义验证器
有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/ValidityState和http://caniuse.com/#feat=input-email-tel-url
答案 9 :(得分:0)
我正在使用: https://www.npmjs.com/package/ng2-validation
npm install ng2-validation --save ng2-validation
我没有回答您的问题,但是对于很多常见情况,您可以找到已经实施的自定义验证器
你的案例中的例子: 电子邮件:['',[CustomValidators.email]]
Best Reagards,