【问题标题】:Is it possible to pass dynamic values to a custom form validator in Angular 6?是否可以将动态值传递给 Angular 6 中的自定义表单验证器?
【发布时间】:2018-09-18 18:31:19
【问题描述】:

基本上,我有一些表单输入,其验证相互依赖(即,如果您输入时间范围,“从”时间必须小于“到”时间),但我并不完全正确确定如何去做。

这是我的表单组:

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 上的文档,但似乎找不到我的答案

【问题讨论】:

  • 您是否尝试在自定义验证函数中返回一个函数?
  • @Nour 这就是我正在做的事情,但似乎我唯一能通过的是正在验证的FormControl
  • 这对你有帮助吗,他们在整个表单上使用验证器? medium.com/@realTomaszKula/…
  • 是的,但是将验证拉到 FormGroup 并没有什么不好。考虑到领域驱动的设计模式,它实际上非常相似,其中实体(此处:FormControl)有时无法验证自己,您需要在服务层(此处:FormGroup)中包含逻辑。关于表单级别的验证,它不亚于字段验证 imo。优点是在一个地方有交叉验证逻辑,您将能够访问所有包含 FormControls 并在两个字段上设置 ValidationErrors。
  • 我完全理解您的担忧。您的问题在模板驱动的表单设计中很容易,但在反应式表单中并不简单。但是,我认为采用这种方法绝对可以(这与 Buczkowski 也建议的几乎相同)

标签: angular typescript angular-reactive-forms angular2-form-validation


【解决方案1】:
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')}}

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

【讨论】:

  • 事实上,这将解决我的问题!一个问题:有没有办法知道特别是什么输入已经改变,以避免每次修改任何输入时都验证我的整个表单?
  • 老实说对此无能为力,我知道某些FormControl 的验证器在验证器函数中获取该表单控件引用作为参数,如果是FormGroup,则表单组引用是通过了。
  • @philr 为什么你不想在每次更改时都运行这个验证器?只要您不触发 http 调用或非常昂贵的计算,就不应该有任何明显的性能损失。
猜你喜欢
  • 2022-11-24
  • 2018-01-12
  • 2020-01-26
  • 2018-05-28
  • 1970-01-01
  • 2023-03-22
  • 2017-03-26
  • 1970-01-01
  • 2017-01-06
相关资源
最近更新 更多