在输入更改时重新评估自定义验证器指令

时间:2020-12-21 07:59:33

标签: angular validation angular-directive

我有一个自定义指令验证器,它使用输入来检查有效性。使用原始值,有效性工作得很好。但是,如果我更新输入,验证器仍然会提示错误并且不会重新评估该值。如何在输入更新时强制重新评估?

指令:

export class TimeRangeValidatorDirective implements Validator {
    @Input() maxTime;
    @Input() minTime;

    validate(control: AbstractControl): ValidationErrors | null {
        return CustomValidators.timeRange(this.maxTime, this.minTime)(control);
    }
}

当最小或最大时间更新时,我想让验证重新运行,以便如果新的最大值高于控制值或新的最小值低于它,以前的错误将不会持续

编辑 基于@Kevin Zhang 给出的答案(为了清晰起见,在此处重写)

解决办法:

export class TimeRangeValidatorDirective implements Validator {
    private _onChange?: ()=>void;
    private _maxTime;
    private _minTime;

    @Input() 
    get maxTime() { return this._maxTime}
    
    set maxTime(value) {
        this._maxTime = value;
        if(this._onChange) {
            this._onChange();
        }
    }

    @Input() 
    get minTime() { return this._minTime}
    
    set minTime(value) {
        this._minTime = value;
        if(this._onChange) {
            this._onChange();
        }
    }

    validate(control: AbstractControl): ValidationErrors | null {
        return CustomValidators.timeRange(this.maxTime, this.minTime)(control);
    }

    registerOnValidatorChanges(fn:()=>void): void {
        this._onChange = fn;
    }
}

1 个答案:

答案 0 :(得分:0)

请参考以下代码使用 getter/setter 并注册验证器更改 fn。

@Directive({
  selector:
      ':not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]',
  providers: [REQUIRED_VALIDATOR],
  host: {'[attr.required]': 'required ? "" : null'}
})
export class RequiredValidator implements Validator {
  private _required = false;
  private _onChange?: () => void;

  /**
   * @description
   * Tracks changes to the required attribute bound to this directive.
   */
  @Input()
  get required(): boolean|string {
    return this._required;
  }

  set required(value: boolean|string) {
    this._required = value != null && value !== false && `${value}` !== 'false';
    if (this._onChange) this._onChange();
  }

  /**
   * @description
   * Method that validates whether the control is empty.
   * Returns the validation result if enabled, otherwise null.
   */
  validate(control: AbstractControl): ValidationErrors|null {
    return this.required ? Validators.required(control) : null;
  }

  /**
   * @description
   * Registers a callback function to call when the validator inputs change.
   *
   * @param fn The callback function
   */
  registerOnValidatorChange(fn: () => void): void {
    this._onChange = fn;
  }
}
相关问题