首页 > 解决方案 > 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();
    }
  }

这是填写所有必要字段并按提交后控制台中的输出:

奇怪的 FormGroup 行为

更新:

我认为表单的状态是“PENDING”,它似乎卡在它上面。我对此也做了很多阅读,但没有一个修复程序对我有用或已经过时。

标签: angularangular-reactive-forms

解决方案


如果您以反应形式验证多个条件,您可能需要像这样使用 Validators.compose:

电子邮件:[null, Validators.compose([Validators.email, Validators.required, this.emailValidator(this.http)])],


推荐阅读