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



基本上,我有一些表单输入,其验证相互依赖(即,如果您要输入时间范围,则"从"时间必须小于"到"时间(,但我不确定如何做到这一点。

这是我的表单组:

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

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

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

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

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

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);
}

在HTML中,您可以通过以下方式进行检查:

{{form.hasError('time')}}

如果您有一些问题,请随时询问。

最新更新