是否可以将动态值传递给 Angular 6 中的自定义表单验证器?

phi*_*ilr 5 typescript angular angular-reactive-forms angular2-form-validation

基本上,我有一些表单输入,它们的验证相互依赖(即,如果您在一个时间范围内,“从”时间必须小于“到”时间),但我不确定如何去做这件事。

这是我的表单组:

this.form = this.fb.group({
  fromTime: ["", [Validators.required, CustomValidator.myValidationFunction(this.form.get("toTime").value)]],
  toTime: ["", [Validators.required]]
});
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我的验证器:

static myValidationFunction(testing) {
    const toTime = testing; // only comes here 1 time
    return control => {
      return toTime /*this value never changes*/  ? null : { test: {} };
    };
  }
Run Code Online (Sandbox Code Playgroud)

但似乎值xortoTime仅在创建验证器时才第一次设置。有没有办法将动态输入传递给自定义验证器?

我对 angular 还很陌生,但已阅读有关自定义表单验证的文档,但似乎找不到我的答案

Buc*_*ski 2

static TimeValidator(formGroup) {
    const fromTime = formGroup.controls.fromTime;
    const toTime = formGroup.controls.toTime;

    if (fromTime.value && toTime.value) {
        if (toTime.value <= fromTime.value) {
            return {time: true};
        }

    }
    return null;
}

ngOnInit(): void {
    this.form = new FormGroup({
        fromTime: new FormControl('', Validators.required),
        toTime: new FormControl('', Validators.required)
    }, AppComponent.TimeValidator);

    this.form.controls.fromTime.setValue(2);
    this.form.controls.toTime.setValue(1);
}
Run Code Online (Sandbox Code Playgroud)

在 html 中,您可以通过以下方式检查:

{{form.hasError('time')}}
Run Code Online (Sandbox Code Playgroud)

如果您有任何疑问,请随时询问。