angular - Angular Custom Validator 导致表单无效
问题描述
我真的很努力想弄清楚这一点,并在 stackoverflow 上阅读了很多类似的问题,但没有任何帮助。
我在 Angular 9 上运行,我正在尝试实现一个自定义验证,如果电子邮件已经存在,它会检查异步。乍一看似乎可以,但是在尝试提交表单时,它说表单无效。但是当检查其中的 FormGroup 对象时,它变得非常valid
奇怪true
。
那就是我的初始化:
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”,它似乎卡在它上面。我对此也做了很多阅读,但没有一个修复程序对我有用或已经过时。
解决方案
如果您以反应形式验证多个条件,您可能需要像这样使用 Validators.compose:
电子邮件:[null, Validators.compose([Validators.email, Validators.required, this.emailValidator(this.http)])],
推荐阅读
- java - Java 并行 GC:不必要的 Full GC
- python - 在线监控python脚本的进度,或在我的手机或另一台计算机上
- kotlin - 当我使用“Navigation-Drawer”KOTLIN 时,我的 Activity 变暗了
- python - 陷入基本的while循环
- css - 在 React 中将 BackgroundImage 与 Overlay 重叠
- asp.net-core - .net 核心未显示 HTML 静态文件更改
- css - 带有 css 的背景形状
- mongodb - 即使投影单个字段,MongoDB 是否会获取整个文档?
- python - python中的Matlab矩阵声明
- python - 参数中的python列表