【发布时间】:2020-10-10 06:49:00
【问题描述】:
我真的在努力解决这个问题,并在 stackoverflow 上阅读了很多类似的问题,但没有任何帮助。
我在 Angular 9 上运行,我正在尝试实现一个自定义验证,如果电子邮件已经存在,它会检查异步。乍一看似乎可以,但是在尝试提交表单时,它说表单无效。但是当检查 valid 是 true 的 FormGroup 对象时,它变得非常奇怪。
这就是我的初始化:
ngOnInit(): void {
this.validateForm = this.fb.group({
academicTitle: [null],
birthday: [null],
firstName: [null, Validators.required],
company: [null],
lastName: [null, Validators.required],
gender: [null],
email: [null, [Validators.email, Validators.required], [this.emailValidator(this.http)]],
password: [null, [Validators.required, Validators.minLength(6)]],
password2: [null, [this.confirmPasswordValidator]],
street: [null],
zip: [null],
city: [null],
country: [null],
role: [null, [Validators.required]],
});
}
这是我的电子邮件验证器
emailValidator(http: HttpClient): ValidatorFn {
return (control: AbstractControl) => {
return http.get(serverConstants.serverUrl + 'user/checkEmail/' + control.value).pipe(map((res) => {
if (res) {
console.log('exists');
return {
error: true,
duplicated: true
};
}
console.log('NOT EXISTING');
return null;
}));
};
}
这里是我的提交方法,正如你所看到的,我确实检查了每个控件是否有效,然后自行形成。它始终输出它在控制台中无效,但实际对象包含valid = true。
submitForm() {
for (const i in this.validateForm.controls) {
this.validateForm.controls[i].markAsDirty();
this.validateForm.controls[i].updateValueAndValidity();
if (this.validateForm.controls[i].invalid) {
console.log(i);
}
}
console.log('is valid ? ' + this.validateForm.valid);
console.log(this.validateForm);
if (this.validateForm.valid) {
this.saveUser();
}
}
这是填写所有必要字段并按提交后控制台中的输出:
更新:
我发现表单的状态是“PENDING”,它似乎卡在上面了。我对此也做了很多阅读,但没有一个修复程序对我有用或者已经过时了。
【问题讨论】:
-
我可以看到 FormGroup 在你的截图中是有效的。
-
@xDrago,你能粘贴整个
SignupComponent类吗?
标签: angular angular-reactive-forms