【问题标题】:Is it possible in Angular reactive forms to validate on conditions out of the form?是否可以在 Angular 反应式表单中验证表单外的条件?
【发布时间】:2019-03-26 12:57:01
【问题描述】:

我正在研究 Angular 反应式表单验证。我有一个使用谷歌自动完成的输入:

<input autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="input-auto input" formControlName="address">

这是标准实现,每次输入一些关键字,你都会得到地点建议:

现在,我想做的是验证地址。 地址需要包含邮政编码 - 只有这样才有效。因此,一旦您输入内容并选择其中一个建议,就应该触发验证。 When chosen suggestion contains zip code is valid, when not - is invalid.

正如您所见,整个地址只有一个表单控件(应该保持这种状态),我用来自 google API 的格式化地址填充。我还从 google places API 中获取了有关地址组件的信息,这些信息存储在全局变量中(zipCode、countryName、cityName、streetName):

    this.mapsAPILoader.load().then(() => {
      const autocomplete = new window['google'].maps.places.Autocomplete(this.searchElementToRef.nativeElement, {
        types: ['address']
      });
      autocomplete.addListener('place_changed', () => {
        this.ngZone.run(() => {

          const place = autocomplete.getPlace();

          if (place.geometry === undefined || place.geometry === null) {
            return;
          }

          this.form.get('address').setValue(place.formatted_address);

          for (const addressComponent of place.address_components) {
            for (const addressComponentType of addressComponent.types) {
              switch (addressComponentType) {
                case 'postal_code':
                  this.zipCode = addressComponent.long_name;
                  break;
                case 'country':
                  this.countryName = addressComponent.long_name;
                  break;
                case 'locality':
                  this.cityName = addressComponent.long_name;
                  break;
                case 'route':
                  this.streetName = addressComponent.long_name;
                  break;
              }
            }
          }
        });
      });
    });

在使用FormBuilder 创建表单的方法中,我使用自定义验证器:

  public createFormGroup(): FormGroup {
    return this.fb.group({
      address: [null, this.zipCodeValidator()]
    });
  }

使用以下自定义验证方法,我想在地址中缺少zipCode 时得到错误:

  public zipCodeValidator(): ValidatorFn {
    return (control: AbstractControl): Observable<{ [key: string]: boolean } | null> => {
      if (this.zipCode !== undefined) {
        return of({ zipCode: true });
      }
      return null;
    };
  }

但是它没有正确验证表单,因为无论我得到的地址有或没有邮政编码 - 它总是有效的:

如果我使用作为条件表单控件相关值的验证,它正在工作。因此,当输入中没有输入任何内容时,将验证方法更新为以下状态会产生错误:

  public zipCodeValidator(): ValidatorFn {
    return (control: AbstractControl): Observable<{ [key: string]: boolean } | null> => {
      if (control.value === null) {
        return of({ noValue: true });
      }
      return null;
    };
  }

问题:
是否可以像这样验证表单 - 条件实际上不在表单中(因为我没有将这个 zipCode 值直接传递给任何表单控件)?

【问题讨论】:

  • TDLR;当您拥有响应式表单时,您实际上拥有的是数据模型。您可以使用该数据模型做任何您想做/需要的事情。因此,您可以在任何需要的条件下进行验证。
  • @Antoniossss 很棒,但是为什么它不起作用呢?我错过了什么?
  • 在您的验证器中,您正在检查this.zipCode,但您需要检查control.value 的邮政编码。
  • @MitchMcCutchen 这实际上是我问过的问题,我知道我应该但我需要吗?
  • 如果您查看从控制台发布的图像,这些属性就是您可以在控件中访问的属性。您可以将参数传递给验证器public zipCodeValidator(zipCode): ValidatorFn { 并进行检查。您需要将您在组件中设置的 zipCode 属性传递给它。

标签: angular typescript validation angular-reactive-forms


【解决方案1】:

答案是,可以根据表格外的条件进行验证,而且通常情况下它离我很近。

首先我搞砸了验证方法。 Observable 我用的是async-validation。所以修复它之后,该方法将只返回对象,而不是 Observable:

  public zipCodeValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value !== null) {
        // if value exists, we can add number of conditions
        if (this.zipCode !== undefined) {
          return { zipCode: true };
        }
      } else {
          // here we can react when there is no value entered - act as validator.required
          return { empty: true}
        }
      return null;
    };
  }

然后我已经开始完成验证,但是对于 zipCode 变量的先前状态。我想是因为也许我需要使用异步验证,但它更简单。我太早设置了地址表单控件的值:this.form.get('address').setValue(place.formatted_address);
所以我把它移到了我正在寻找邮政编码的部分后面,它起作用了:

this.mapsAPILoader.load().then(() => {
  const autocomplete = new window['google'].maps.places.Autocomplete(this.searchElementToRef.nativeElement, {
    types: ['address']
  });
  autocomplete.addListener('place_changed', () => {
    this.ngZone.run(() => {

      const place = autocomplete.getPlace();

      if (place.geometry === undefined || place.geometry === null) {
        return;
      }

      for (const addressComponent of place.address_components) {
        for (const addressComponentType of addressComponent.types) {
          switch (addressComponentType) {
            case 'postal_code':
              this.zipCode = addressComponent.long_name;
              break;
            case 'country':
              this.countryName = addressComponent.long_name;
              break;
            case 'locality':
              this.cityName = addressComponent.long_name;
              break;
            case 'route':
              this.streetName = addressComponent.long_name;
              break;
          }
        }
      }

      this.form.get('address').setValue(place.formatted_address);
    });
  });
});

还有一个问题是,如果我想在其他时刻触发验证,而不是从头开始。然后只需将其设置在正确的位置并更新验证器:

this.form.get('address').setValidators(this.zipCodeValidator());
this.form.get('address').updateValueAndValidity();

此外,如果需要在某些时候将其删除,这里是简单的方法:

this.form.get('address').clearValidators();

【讨论】:

    猜你喜欢
    • 2019-05-04
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多