Angular2相互依赖的表单字段验证 [英] Angular2 interdependent form field validation

查看:88
本文介绍了Angular2相互依赖的表单字段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表单字段,如果填写了第一个字段,则第二个字段是必填字段.如果我尝试使用自定义验证程序在Angular2中执行此操作,则仅在初始化以及更改特定字段时才触发验证程序.

I have two form fields, where if the first field is filled in, the second field is mandatory. If I try to do this in Angular2, using a custom validator, the validator is only fired on initialization and when the specific field is changed.

情况: -用户填写字段1 -字段2应该成为必填字段,但直到用户实际更改字段2(触发自定义验证)后,该字段才变为必需.

Case: - User fills in field 1 - Field 2 should become required, but isn't till the user actually changes field 2 (firing the custom validation).

private createForm():void {
 this.testForm = this._formBuilder.group({
  'field1': [],
  'field2': ['', this.validateRequired()]
 });
}

private validateRequired(){
 console.log("something", this);
 let component = this;

 return (control: Control): { [s: string]: boolean } => {
   return component.testModel.field1 && !control.value {"required":true} : null;
 }
}

请参阅以下示例: http://plnkr.co/edit/PEY2QIegkqo8BW1UkQS5?p=preview

目前,我订阅了field1的valueChange observable,并在更改后对field2进行了手动检查,例如:

For now I subscribed to field1's valueChange observable and when changed execute a manual check on field2, like:

this.testForm.controls['field1'].valueChanges.subscribe(
  value => {
   component.testForm.controls['field2].updateValueAndValidity();        
  }
)

但是我觉得必须有更好的方法来做到这一点.

But I feel like there must be a better way to do this.

推荐答案

您可以为此类使用全局验证器:

You could use a global validator for the group like this:

private createForm():void {
 this.testForm = this._formBuilder.group({
  'field1': [],
  'field2': ['', this.validateRequired()]
 }, {
  validator: this.someGlobalValidator // <-----
 });
}

someGlobalValidator(group: ControlGroup) { // <-----
  var valid = false;

  for (name in group.controls) {
    var val = group.controls[name].value

    (...)
  }

  if (valid) {
    return null;
  }

  return {
    someValidationError: true
  };
}

这篇关于Angular2相互依赖的表单字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆