在 angular 反应形式中使用自定义验证器

Using Custom validators in angular reactive form

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

代码:

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 nullif (control.value !== undefined && (isNaN(control.value) || control.get('fromTime').value > control.get('toTime').value))

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

您的自定义验证器应该放在 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 key-value 对。例如。 isEndGTStart:如果为 false

,则为 true 或 null

例如

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

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