【问题标题】:How to force validation for disabled property?如何强制验证禁用的属性?
【发布时间】:2019-04-05 04:30:28
【问题描述】:

我有一个表单元素如下:

<input type="text" id="country" formControlName="Country" />

我的表单组如下:

 this.myForm = this.formbuilder.group({
            'Country': [{ value: this.user.Country, disabled: this.SomeProperty===true}, [Validators.required]],
});

this.SomePropertytrue 时禁用时,所需的验证器根本不起作用并且启用Save 按钮。

<button type="submit" [disabled]="!myForm.valid">Save</button>

是否有强制验证禁用属性?

required 属性可以为 null 的原因是由于某些数据问题或数据从不同的源迁移而没有所需的值,这是我无法控制的。

【问题讨论】:

  • 可以这样调用函数:[disabled]="validationFunction()" 并根据不同情况返回真假
  • 不禁用FormControl,使用[attr.disabled]="condition"(这禁用了输入但没有禁用FormControl)

标签: html angular typescript


【解决方案1】:

嗯.. 一般来说,Angular Reactive Forms 不会触发禁用表单字段的验证器。

我可以建议您解决这种情况的两种方法:

1) 在您的 FormGroup 上编写自定义验证器以手动检查每个单独的表单控件的值。

this.myForm = this.formbuilder.group({
  'Country': [{ value: this.user.Country, disabled: this.SomeProperty===true}, [Validators.required]],
   // other FormControls
}, { validator: GroupValidator.checkEveryField() });

然后,创建一个新的 Validator 类来检查空的Country FormControl。如果为空,则返回验证错误。

import { AbstractControl } from '@angular/forms';

export class GroupValidator {

  static checkEveryField(control: AbstractControl) {
    const { Country } = control.value;
    if (!Country) {
      return { 'invalidCountry': true };
    } else {
      return null;
    }
  }
}

2) 在将值修补到 FormGroup 之前,编写一个检查传入数据值的方法。

this.someService.getData().subscribe(response => {
  if (!response.user.Country) {
    // trigger invalid validation response
  } else {
    this.myForm.patchVaue(response.user);
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多