gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:56:12 27 4
gpt4 key购买 nike

基本上,我有一些表单输入,它们的验证相互依赖(即如果你输入一个时间范围,“从”时间必须小于“到”时间)但我不完全确定如何解决这个问题。

这是我的表单组:

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 还很陌生,但已经阅读了 custom form validation 上的文档但似乎找不到我的答案

最佳答案

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

如果您有任何问题,请随时提出。

关于angular - 是否可以将动态值传递给 Angular 6 中的自定义表单验证器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52392640/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com