Validate field depending on the value of another Angular

1

I request your collaboration to indicate how I can validate a text field that depends on the selected value in a Radio button; really what I need is to activate the observations field only if option 4 is selected, but the form shows it as invalid.

Class

Class

export class AppComponent {

  testForm: FormGroup;
  msgError: string = 'Este Campo es obligatorio';

  opciones = [
    { nombre: 'N1', valor: 1 },
    { nombre: 'N2', valor: 2 },
    { nombre: 'N3', valor: 3 },
    { nombre: 'Otra Respuesta', valor: 4 },
  ];

  constructor(public fb: FormBuilder) {

    this.testForm = this.fb.group({
      'opcionA': ['', [Validators.required]],
      'observacionA': new FormControl(null)
    }, {
        validator: this.specificValue
      });
  }

  valido(): boolean {
    return !this.testForm.valid;
  }

  specificValue(group: any) {
    if (!group.controls.opcionA || !group.controls.opcionA.value) return;

    const opcionA = group.controls.opcionA.value;
    let observacionA = group.controls.observacionA.value;
    if (opcionA == '4') {
      if (observacionA) {
        return {
          return: null
        };
      } else {
        return {
          isRequired: true
        };
      }
    }
  }

  guardar() {
    console.log(this.testForm.value);
  }

}

Html

<h1>Form</h1>

<form [formGroup]="testForm" (ngSubmit)="guardar()" novalidate>
  <label *ngFor="let opcion of opciones">
  <input type="radio" 
        formControlName="opcionA"
        required
        [value]="opcion.valor">{{opcion.nombre}}
</label>
  <div *ngIf="testForm.get('opcionA').invalid">
    {{ msgError }}
  </div>
  <div *ngIf="testForm.value.opcionA === 4">
    <textarea formControlName="observacionA"></textarea>
    <div *ngIf="testForm.get('observacionA').invalid">
      {{ msgError }}
    </div>
  </div>
<br>
<hr>
  <button [disabled]="valido"
          type="submit">
  Save
</button>
</form>

{{testForm.valid}}

Demo in stackblitz

    
asked by Gdaimon 02.10.2017 в 04:17
source

1 answer

1

The validation function must comply with the following signature:

interface ValidatorFn { 
  (c: AbstractControl): ValidationErrors|null
}

Your function does not comply when option is not 4, since you do not enter the block if and therefore nothing is returned. That is equivalent to returning undefined , which is not the same as null .

When option is 4, then, if observationA is a "true" value, you are not returning null, but an object equivalent to the following:

let obj= {
    return: null
}

With which you do not return what the framework expects.

    
answered by 02.10.2017 / 09:44
source