Gdaimon Gdaimon - 3 years ago 173
Javascript Question

Validate field depending on the value of another Angular

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

When I select option four it tells me that it is required of the field observacionA, but when I fill it the form follows invalid

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

Answer Source

When validator is valid you should return null not object like:

{
  return: null
}

It should be:

if(observacionA){
  return null;

One more note:

<button [disabled]="valido()"
                          ^^^
                     add this because it's method

Stackblitz example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download