【问题标题】:Angular Custom Validator causes form to be invalidAngular Custom Validator 导致表单无效
【发布时间】:2020-10-10 06:49:00
【问题描述】:

我真的在努力解决这个问题,并在 stackoverflow 上阅读了很多类似的问题,但没有任何帮助。

我在 Angular 9 上运行,我正在尝试实现一个自定义验证,如果电子邮件已经存在,它会检查异步。乍一看似乎可以,但是在尝试提交表单时,它说表单无效。但是当检查 validtrue 的 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


【解决方案1】:

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

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

【讨论】:

  • 不幸的是,这不能解决我的问题。当我执行console.log 时,我不明白为什么valiateForm.valid 是错误的。但是在那之后立即记录对象本身时,这是真的。
  • console.log(this.validateForm);
【解决方案2】:

您可能应该实现AsyncValidatorFn,因为 HTTP 请求是异步的。在我看来,您的日志一目了然,您的表单当时无效,并在您检查控制台时生效。 Chrome 的控制台仅在您单击它时评估对象值。如果您在 console.log 的确切时刻需要对象值,请尝试console.log(JSON.stringify(this.validateForm))

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 1970-01-01
    • 2019-01-09
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2014-04-25
    • 1970-01-01
    相关资源
    最近更新 更多