我想创建一个用户将输入他的邮件的表单。
我想验证客户端的邮件格式。
Angular2中是否有任何通用的邮件验证器?
我想验证客户端的邮件格式。
Angular2中是否有任何通用的邮件验证器?
注意:与angularjs验证器类似的东西:https://docs.angularjs.org/api/ng/input/input%5Bemail%5D
您可以使用表单指令和控件来执行此操作。
原文链接:https://www.f2er.com/angularjs/144809.htmlexport 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。