我正在使用表單驗證,其中表單包含一個電子郵件字段,並且是文本類型(即)input [type ='text']。我使用模式驗證電子郵件,這意味着使用RegExp進行自定義驗證。在Angular2中使用模式進行電子郵件驗證的最佳方式是什麼?
現在我的問題是我可以驗證該字段是否爲空。但是,在進行模式驗證時,我無法按預期得到結果。
所以我需要的是一種使用Angular2驗證模式的方法。
我正在使用表單驗證,其中表單包含一個電子郵件字段,並且是文本類型(即)input [type ='text']。我使用模式驗證電子郵件,這意味着使用RegExp進行自定義驗證。在Angular2中使用模式進行電子郵件驗證的最佳方式是什麼?
現在我的問題是我可以驗證該字段是否爲空。但是,在進行模式驗證時,我無法按預期得到結果。
所以我需要的是一種使用Angular2驗證模式的方法。
如果您在使用Angular2反應形式(我認爲它排在4.2.5版本)可以設置表單控件將使用驗證器,它有內置的電子郵件驗證。
請參閱角文檔更多信息。
https://angular.io/api/forms/Validators
編輯:
下面是一個例子Plunker與它一起工作。
下面是代碼
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<form [formGroup]="userform">
<div class="form-group">
<input type="text" formControlName="userEmail" />
<p *ngIf="userform.get('userEmail').hasError('email') && !userform.controls['userEmail'].valid && userform.get('userEmail').touched">Email is invalid.</p>
</div>
</form>
`,
})
export class App implements OnInit {
userform: FormGroup;
constructor(private _fb: FormBuilder) { }
buildForm() {
this.userform = this._fb.group({
userEmail: [null, Validators.email]
});
}
ngOnInit() {
this.buildForm();
}
}
@NgModule({
imports: [ BrowserModule, FormsModule, ReactiveFormsModule, ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
現在,您可以簡單地使用email
作爲屬性(在angular4指令)現在的角度來驗證電子郵件驗證這樣
<input type="email" name="email" ngModel email>
副本
欲瞭解更多信息,你可以在這裏參考
你可以舉一些例子對這個 – Ram
@Ram添加一個例子,你 –
謝謝你的例子 – Ram