【问题标题】:Validation for Either-Or Field Logic in Angular Reactive Forms, in City/State or zip在 Angular Reactive Forms、City/State 或 zip 中验证非此即彼的字段逻辑
【发布时间】:2020-03-30 21:57:36
【问题描述】:

无论如何要在 Angular Reactive Forms 中进行“要么,要么,一个或另一个验证”?

目前,希望表单有效,(a)如果输入了城市和州或(b)输入了邮政编码,任一组,并且表单有效。 如果两个组都为空,则表单无效。

这是基本的开始形式,目前 city 和 zip 都是可选的,试图结合这个正确的逻辑。

public editAddressForm: FormGroup;

this.editAddressForm = this.formBuilder.group({

      'name': [null, [Validators.maxLength(100)]],
      'phonenumber': [null, [Validators.maxLength(50)]],
      'city': [null, [Validators.maxLength(32)]],
      'state': [null,[Validators.maxLength(4)]],
      'zipcode': [null, [Validators.maxLength(16)]]
    })

尝试使用此资源,但它需要嵌套 city 和 zip,这不是必需的。

Angular, How to set validation for either of two field should validate in reaction form approach

【问题讨论】:

标签: angular typescript angular-reactive-forms angular8


【解决方案1】:

首先创建函数,然后将此验证器应用于表单。

export function atLeastOneLocationRequired(group : FormGroup) : {[s:string ]: boolean} {
  var cityCtrl = group.controls.city;
  var stateCtrl = group.controls.state;
  var postalCodeCtrl = group.controls.postalCode;

  if (cityCtrl != undefined && stateCtrl != undefined && postalCodeCtrl != undefined)
    if (!(((cityCtrl.value && cityCtrl.value.length) && (stateCtrl.value && stateCtrl.value.length)) || (postalCodeCtrl.value && postalCodeCtrl.value.length)))
      return { invalid: true };
}

this.editAddressForm = this.formBuilder.group({
      'name': [null, [Validators.maxLength(100)]],
      'phonenumber': [null, [Validators.maxLength(50)]],
      'city': [null, [Validators.maxLength(32)]],
      'state': [null,[Validators.maxLength(4)]],
      'zipcode': [null, [Validators.maxLength(16)]]
    }, { validator: atLeastOneLocationRequired })

【讨论】:

    【解决方案2】:

    您可以为可以访问表单中所有字段的表单编写自定义验证器。然后它可以检查这两个字段中的任何一个的值并根据需要返回 true/false。

    Angular 文档称之为跨字段验证。你可以在docs here阅读它。

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 1970-01-01
      • 2021-08-30
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 2019-01-04
      相关资源
      最近更新 更多