我正在处理 Angular 反应式表单验证,但我无法验证电子邮件。
每次在电子邮件输入字段中输入时,我都会遇到错误-
ReactiveComponent.html:21 ERROR Error: Expected validator to return Promise or Observable.
at toObservable (forms.js:456)
at Array.map (<anonymous>)
at FormControl.asyncValidator (forms.js:444)
at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runAsyncValidator (forms.js:2313)
at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl.updateValueAndValidity (forms.js:2286)
at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.FormControl.setValue (forms.js:2624)
at updateControl (forms.js:1558)
at DefaultValueAccessor.onChange (forms.js:1543)
at DefaultValueAccessor.push../node_modules/@angular/forms/fesm5/forms.js.DefaultValueAccessor._handleInput (forms.js:601)
at Object.eval [as handleEvent] (ReactiveComponent.html:21)
我将我的代码放在 ts 文件和 html 文件中
ts 文件 -
import { Component, OnInit } from '@angular/core';
import {FormGroup, FormControl , FormBuilder, NgForm , Validators} from '@angular/forms';
@Component({
selector: 'app-reactive',
templateUrl: './reactive.component.html',
styleUrls: ['./reactive.component.css']
})
export class ReactiveComponent implements OnInit {
signupForm: FormGroup;
FirstName: string = '';
LastName: string = '';
Eamil: string = '';
Password: string = '';
constructor(public frmbuilder: FormBuilder) { // formBuilder assign all the formcontrol to formgroup
this.signupForm = frmbuilder.group({
fname: ['', Validators.required], // FormControl Used to bring input value to the ts file
lname: ['', Validators.required],
Emailid: ['', Validators.required , Validators.email],
userpassword: ['', Validators.required ]
});
}
ngOnInit() {
}
PostData(signupForm: any) {
console.log(signupForm.controls);
this.FirstName = signupForm.controls.fname.value;
this.LastName = signupForm.controls.lname.value;
this.Eamil = signupForm.controls.Emailid.value;
this.Password = signupForm.controls.userpassword.value;
}
}
HTML 文件 ->
注意 -> Button is disabled ,在表单字段验证后,按钮将被启用。我使用了 Validators.email 所以,如果我写一封有效的电子邮件,例如 - anurag@gmail.com 并填写所有输入,按钮永远不会启用 但是当我删除 Validators.email并填写所有输入按钮时启用
<form [formGroup]='signupForm' (ngSubmit)="PostData(signupForm)">
<div class="form-group">
<input type="text" formControlName='fname' placeholder="First Name">
</div>
<div class="form-group">
<input type="text" formControlName='lname' placeholder="last Name">
</div>
<div class="form-group">
<input type="email" formControlName='Emailid' placeholder="Eamil Id">
</div>
<div class="form-group">
<input type="password" formControlName='userpassword' placeholder="your pasword">
</div>
<div>
<input type="submit" value="Post Data" [disabled]='!signupForm.valid'>
</div>
</form>