如何验证依赖于另一个表单控件的响应式表单控件?

时间:2017-06-23 13:45:07

标签: angular angular2-forms angular-forms

Angular Form组件类是:

export class SpecsFilterFormComponent implements OnInit {

  specFilterForm: FormGroup;
  cameraSizeMin = new FormControl("", [Validators.pattern("\s*|[0-9.]*")]);
  cameraSizeMax = new FormControl("", [Validators.pattern("\s*|[0-9.]*")]);

  constructor(private fb: FormBuilder) {    }

  ngOnInit() {

  this.specFilterForm = this.fb.group({
  cameraSize: this.fb.group(
    {
      cameraSizeMin: this.cameraSizeMin,
      cameraSizeMax: this.cameraSizeMax,
    })
});

this.specFilterForm.valueChanges.debounceTime(500).filter(
  formData => this.specFilterForm.valid)
  .subscribe(
    formData => {
      console.log("do something after validation")
    });
  }
  }

我想添加验证以确保cameraSizeMax> = cameraSizeMin,如何在from control cameraSizeMin和cameraSizeMax中应用此验证。

1 个答案:

答案 0 :(得分:2)

我创建了一个应用于完整表单组的自定义验证器,然后在表单控件中添加错误:

以下将cameraSizeMin设置为无效。

class CustomValidator {
  static validate(abstractForm: FormGroup): {[key: string]: any} => {
    let cameraSizeMin = abstractForm.get("cameraSizeMin");
    let cameraSizeMax = abstractForm.get("cameraSizeMax");

    //validation logic in condition below
    if (true) {
      cameraSizeMin.setErrors({"customValidation": true});
    }
  }
}

您可以通过以下方式将其注册到formGroup:

this.specFilterForm = this.fb.group({
  cameraSize: this.fb.group(
    {
      cameraSizeMin: this.cameraSizeMin,
      cameraSizeMax: this.cameraSizeMax,
    }, {validator: CustomValidator.validate}
  )
});