Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 - Validate input field only if checkbox is checked

I'm using angular 7 and I have a form with two input fields, while the first one is always required, the second one should be required only if a checkbox is checked.

I'm trying to use a FormGroup with a custom validator:

<form [formGroup]="exampleForm">
  <mat-form-field>
    <input matInput placeholder="first" formControlName="first">
  </mat-form-field>
  <mat-checkbox [(ngModel)]=" checked" [ngModelOptions]="{standalone:true}">Make second input field required</mat-checkbox>
  <mat-form-field>
    <input matInput placeholder="second" formControlName="second">
  </mat-form-field>
</form>

exampleForm: FormGroup;
checked: boolean;

ngOnInit() {
  this.exampleForm = new FormGroup({
    'second': new FormControl('', [this.validateIfChecked()]),
    'first': new FormControl('example', [Validators.required])
  });
}


validateIfChecked(): ValidatorFn {
  return (control: AbstractControl): {
    [key: string]: any
  } | null => {
    if (this.checked) {
      return control.value ? null : {
        'err': true
      };
    }
    return null;
  }
}

The problem is that the validation is performed only when the text in the two input fields is updated, while if I check/uncheck the checkbox the state doesn't change and to force the validation I have to change the text in the second textbox.

Here you can see an example on stackblitz: if you check the checkbox, the status doesn't change.

How can can I force the validation when the checkbox status changes?

like image 639
matte_colo Avatar asked Feb 21 '19 16:02

matte_colo


Video Answer


2 Answers

You need to use crossfield validation. Include the checkbox in your formgroup

<form [formGroup]="exampleForm">
    <mat-form-field>
    <input matInput placeholder="first" formControlName="first">
    </mat-form-field>
    <mat-checkbox formControlName="checked">Make second input field required</mat-checkbox>
    <mat-form-field>
    <input matInput placeholder="second" formControlName="second">
    </mat-form-field>
</form>
ngOnInit() {
    this.exampleForm = new FormGroup({
    'second': new FormControl(''),
    'checked': new FormControl(false),
    'first': new FormControl('example')
    }, [this.validateIfChecked()]);
}


validateIfChecked(): ValidatorFn {
    return (form: FormGroup): ValidationErrors | null => {
    const checked = form.get('checked');
    const second= form.get('second');
    if (checked && !second) {
        return {
        'err': true
        };
    }
    return null;
    }
}

In this case, if 'checked' is true then 'second' is required

if in doubt https://angular.io/guide/form-validation#cross-field-validation

like image 132
Joey Gough Avatar answered Oct 11 '22 14:10

Joey Gough


If you actually don't want to include the checkbox value to your form, you can make a separate form control, which is not included in your form. Based on the checkbox value you can clear validators or add required validator:

checked = new FormControl(false);

// ...

this.checked.valueChanges.subscribe((bool: boolean) => {
  bool ? this.exampleForm.get('second').setValidators(Validators.required) : 
         this.exampleForm.get('second').clearValidators();
  this.exampleForm.get('second').updateValueAndValidity();
});

And the relevant template:

<mat-checkbox [formControl]="checked">Make second input field required</mat-checkbox>

Your forked StackBlitz

like image 40
AT82 Avatar answered Oct 11 '22 14:10

AT82