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


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 ={
'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() {




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


Demo in stackblitz

Answer Source

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

  return: null

It should be:

  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