Angular 2或4 Reactive表单集验证取决于另一个字段值

时间:2017-08-07 11:48:17

标签: angular typescript angular2-forms angular2-formbuilder

我尝试使用Reactive Forms模块在Angular 2中构建一个表单,并且我试图以另一个字段选择所需的形式设置某个字段的验证。
我做错了什么?

ngOnInit() {
    this.martialForm = this.fb.group({
        'maritalStatus': [this.model.maritalStatus, [Validators.required]],
        'spouseTitle': [this.spouseModel.title, null]
    },{
         validator: this.validateIsSpouse
    })
}

validateIsSpouse(group: FormGroup) {
    if(this.model.maritalStatus == "01"){
        group.controls['spouseTitle'].setErrors({ isRequired: true });
    }

    return null;
}

1 个答案:

答案 0 :(得分:6)

自定义验证函数在import语句后立即写入,代码和验证器应按以下方式编写:

// import statement

function validateIsSpouse(group: FormGroup) {
  let maritalStatus = group.get('maritalStatus').value;
  if(maritalStatus == "01"){
    retun { isRequired: true };
  }
  return null;
}

// @Component

export class MyClass implements OnInit {

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.martialForm = this.fb.group({
      'maritalStatus': [this.model.maritalStatus, [Validators.required]],
      'spouseTitle': [this.spouseModel.title, null]
    },{ validator: validateIsSpouse });
  }

}