【问题标题】:Using Custom validators in angular reactive form以角度反应形式使用自定义验证器
【发布时间】:2019-06-07 22:40:35
【问题描述】:

我正在尝试使用自定义验证器来比较结束时间是否大于开始时间。

代码:

function timeValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value !== undefined && (isNaN(control.value) || control.get('fromTime').value > control.get('toTime').value)) {
          return { 'ageRange': true };
      }
      return null;
  };
}

来自表单组

toTime: new FormControl(null, [Validators.required, timeValidator(this.fromTime,this.toTime)]),

一旦我像这样运行以下命令,我会遇到错误:Cannot read property 'value' of null 在线 if (control.value !== undefined && (isNaN(control.value) || control.get('fromTime').value > control.get('toTime').value))

我需要一些帮助来解决这个问题。谢谢

【问题讨论】:

  • 你能把代码分享到stackblitz.com
  • 您正在调用验证器,而不是将函数作为参数传递
  • 谢谢,有一个例子很好学习。@AvinKavish

标签: angular angular7 angular-reactive-forms


【解决方案1】:

您的自定义验证器应该放在 FormGroup 级别而不是 FormControl 级别。此外,您应该将函数作为参数传递,这意味着没有 () 括号,因为 timeValidator 是一个回调函数。 () 告诉 js 引擎执行该函数。但是你想要的是将函数作为参数传入,以便稍后执行。

要么

constructor(private fb: FormBuilder){}
...
this.form = this.fb.group({
    fromTime: [''],
    toTime: ['']
}, { validator: timeValidator})

 form = new FormGroup({
     toTime: new FormControl(null),
     fromTime: new FormControl(null),
 }, { validator: timeValidator})

您的自定义验证器也不应该返回函数。它应该返回一个 name:boolean 键值对。例如。 isEndGTStart: true 或 null 如果为 false

例如

export function timeValidator(fg: FormGroup){
    const fromTime = fg.get("fromTime").value;
    const toTime = fg.get("toTime).value;

    return toTime > fromTime ? { isEndGTStart: true } : null
}

【讨论】:

    猜你喜欢
    • 2017-10-06
    • 2018-04-02
    • 1970-01-01
    • 2019-07-26
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多