【问题标题】:multi same custom validator function in reactive form constructor反应形式构造函数中的多个相同的自定义验证器函数
【发布时间】:2020-03-04 14:28:40
【问题描述】:

我需要一点帮助来了解如何在同一个构造函数中对不同的 formControl 多次使用相同的自定义验证器函数,该函数使用 formControl 作为参数来了解 time1 > time2,并且我有 3 个不同的时间 formControl,但我不知道如何使用相同的函数来验证所有的 formControls,这是我的自定义函数验证器:

/ custom validator to check if time 1 is after time 2
export function timeIsAfter(time1Control: string, time2Control: string) {
  
    return (formGroup: FormGroup) => {
        const time1 = formGroup.controls[time1Control];
        const time2 = formGroup.controls[time2Control];

        if (time2.errors && !time2.errors.timeIsAfter) {
            // return if another validator has already found an error on the matchingControl
            return;
        }

        // set error on matchingControl if validation fails
        if (time1.value > time2.value) {
            time1.setErrors({ timeIsAfter: true });
        } else {
            time1.setErrors(null);
        }
    }
}

这是我的表单构造函数:

formConstructor() {
  this.frequencyForm = this.formBuilder.group({
    time_1: new FormControl(null),
    time_2: new FormControl(null),
    time_3: new FormControl(null),
    time_4: new FormControl(null),

   
  }, {
    validator: timeIsAfter('time_1', 'time_2'), // <--- this works 
    validator_2: timeIsAfter('time_3', 'time_4'), // <--- this doesnt work
  });
}

我尝试使用 Validators.compose 添加但不起作用,也使用 Validators.call 并且出现错误

欢迎任何帮助

【问题讨论】:

    标签: angular typescript angular8


    【解决方案1】:

    像这样设置验证器数组而不是对象。 还要设置返回函数的类型为ValidatorFn

    formConstructor() {
        this.frequencyForm = this.formBuilder.group({
          time_1: new FormControl(null),
          time_2: new FormControl(null),
          time_3: new FormControl(null),
          time_4: new FormControl(null),
        });
        this.frequencyForm.setValidators([timeIsAfter('time_1', 'time_2'), timeIsAfter('time_3', 'time_4')])
      }
    
    export function timeIsAfter(time1Control: string, time2Control: string) {
    
        return (formGroup: FormGroup): ValidatorFn => { ... }
    
    }
    

    【讨论】:

    • 我收到此错误:'((formGroup: FormGroup) => void)[]' 类型的参数不可分配给'ValidatorFn |验证器Fn[]'。类型 '((formGroup: FormGroup) => void)[]' 不可分配给类型 'ValidatorFn[]'。类型“(formGroup:FormGroup)=> void”不可分配给类型“ValidatorFn”。类型 'void' 不可分配给类型 'ValidationErrors'.ts(2345)
    • 设置返回的函数类型为ValidatorFn
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多