Angular 4 remove required validator conditionally

后端 未结 10 1945
[愿得一人]
[愿得一人] 2021-02-01 01:26

In Angular 4 app I have a form model like this:

this.form = this._fb.group({
    title: [\'\', [Validators.required, Validators.minLength(3), Validators.maxLengt         


        
10条回答
  •  臣服心动
    2021-02-01 02:04

    I don't like clearing and setting validators, as I have to repeat all static validators (patterns, min, max, etc.) just to have a dynamic "required" validator.

    I use a conditional validator:

    export function conditionalValidator(condFn: (control: AbstractControl) => boolean,
    validators: ValidatorFn | ValidatorFn[]): ValidatorFn {
      return (control) => {
        if (!condFn(control)) {
          return null;
        }
    
        if (!Array.isArray(validators)) {
          return validators(control);
        }
    
        return validators.map(v => v(control)).reduce((errors, result) =>
          result === null ? errors :
            (Object.assign(errors || {}, result))
        );
      };
    }
    

    I can then mix a static validator with a dynamic "required" condition:

    this.fb.group({name: ['', [Validators.minLength(4),
                     conditionalValidator(this.isClientProj, Validators.required)]]}
    

    Where isClientProj() is the condition function (closure)

提交回复
热议问题