Angular reactive forms set and clear validators
Asked Answered
T

2

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.

Tryparsamide answered 12/7, 2018 at 8:22 Comment(0)
M
63

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();
    }
}
Microelement answered 12/7, 2018 at 8:47 Comment(1)
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.Peyote
H
-1

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);               
                }
            }  
    }
}
Houseclean answered 12/4, 2023 at 4:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.