29

Please assist, I want to remove all validators in form, Please advise whether it's possible or not and if not, what's the better way to remove validators if you have a form Group of 20 or more form controls, see example below.

 ngOnInit() {
    this.exampleFormGroup = this.formBuilder.group({
     surname: ['', [Validators.required, Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]],
     initials: ['', [Validators.required, Validators.maxLength(4)]]
     });
  }

 public removeValidators() {
    this.exampleFormGroup.get('surname').clearValidators();
    this.exampleFormGroup.get('initials').clearValidators();
    this.exampleFormGroup.updateValueAndValidity();
 }

 public addValidators() { 
  this.exampleFormGroup .get('surname').setValidators([Validators.required,Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]);
  this.exampleFormGroup.get('initials').setValidators([Validators.required, Validators.maxLength(4)]);
  this.exampleFormGroup.updateValueAndValidity(); 
 }

The above method addValidators() will add validators and removeValidators() will remove validators when executed. But the problem I have is, I have to specify the form control I'm trying to clear validators. Is there a way to just do this.exampleFormGroup.clearValidators(); and clear all in the form and again this.exampleFormGroup.setValidators() to set them back? I know I may be asking for a unicorn, but in a scenario where the formGroup has 20 or more controls, clearing and setting validators can be painful, so a map on how to handle such scenarios will be much appreciated.

0

2 Answers 2

64

You can do something like this:

validationType = {
    'surname': [Validators.required, Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')],
    'initials': [Validators.required, Validators.maxLength(4)]
}

ngOnInit() {
    this.exampleFormGroup = this.formBuilder.group({
        surname: ['', [Validators.required, Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]],
        initials: ['', [Validators.required, Validators.maxLength(4)]]
    });
}

public removeValidators(form: FormGroup) {
    for (const key in form.controls) {
        form.get(key).clearValidators();
        form.get(key).updateValueAndValidity();
    }
}
     

public addValidators(form: FormGroup) {
    for (const key in form.controls) {
        form.get(key).setValidators(this.validationType[key]);
        form.get(key).updateValueAndValidity();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. I had the same problem. form.get(key).clearValidators(); form.get(key).updateValueAndValidity(); solved my issue. Note: If someone calls the method inside form.valueChanges.pipe().subscribe(...) and still makes changes inside the same, should remember to set form.get(key).updateValueAndValidity({withEvents: false}), otherwise you will get into an infinite loop, leading to a stack overflow problem.
-2

Agregando y quitando de un arreglo FormArray

constructor(  private fb: FormBuilder){
 public ngOnInit() {

        super.ngOnInit();
 this.form = new FormGroup({
'listaComensales' : this.fb.array([]), 
});
}   
/**
     * Quitar validaciones 
     * @param key id de formulario
     */
    private removeValidation( key: string, form: FormGroup): void {
        const refSingle = form.get(key) as FormGroup;
        refSingle.clearValidators();
        refSingle.updateValueAndValidity();

    }

    /**
     * Agregar validaciones
     * @param key id de formulario
     * @param val validadores
     */
    private addValidation( key: string,val: ValidatorFn[], form: FormGroup): void {
            const refSingle = form.get(key) as FormGroup;
            refSingle.setValidators(val);
            refSingle.updateValueAndValidity();
    }
//lista de un arreglo formulario
get listaArray() {
        return this.form.get('listaArray') as FormArray;
    }

//agregando fila al formulario
    public addFila(element: any = null) {

        let fila: any;

            fila= this.fb.group({
                dato1: new FormControl(element.empresa, [Validators.required, Validators.maxLength(4)]),
                dato2: new FormControl(element.cdEmpleado,[Validators.required, Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]),
                });

        this.listaArray.push(fila);
    }

// Agregar validacion al arreglo
private validarAreglo(){
            const validationType = {
                'dato1': [Validators.required, Validators.maxLength(4)],
                'dato2': [Validators.required, Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')],
                
            }
            for(const key in this.fila.controls){             
                const refSingle = this.fila.get(key) as FormGroup;
                for(const k in refSingle.controls){  
                    this.addValidation(k,validationType[k],refSingle);            
                }
            }
}

//Quitando las validaciones de arreglo
public quitarValidArreglo(){
            for(const key in this.fila.controls){             
                const refSingle = this.fila.get(key) as FormGroup;
                for(const k in refSingle.controls){
                    // refSingle.get(k).clearValidators();
                    // refSingle.get(k).updateValueAndValidity();     
                    this.removeValidation(k,refSingle);               
                }
            }  
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.