Home > Software design >  Angular Reactive Form - How to validate radio buttons and show error message when form is submitted
Angular Reactive Form - How to validate radio buttons and show error message when form is submitted

Time:12-23

Goal: Make the radio buttons required.

Issue: The element mat-error and its contents are displaying right off the bat, without the form submitted. The element mat-error and its content should only display when the user attempts to submit the form.

I tried adding the on-touch criteria but I could not get it to work!

Any advice is welcome!

HTML:

<div >
  <label >Channel visibility</label>
  <mat-radio-group formControlName="visibility" aria-label="Select an option">
    <mat-radio-button value="public">Public</mat-radio-button>
    <mat-radio-button value="private">Private</mat-radio-button>
    <!-- fix: touched is not working -->
    <mat-error *ngIf="form.get('visibility').invalid">Please select channel visibility.</mat-error>
  </mat-radio-group>

</div>

Component:

initializeFormAndItsFields() {
  this.form = new FormGroup({
    title: new FormControl(null, {
      validators: [Validators.required, Validators.minLength(3)]
    }),
    visibility: new FormControl(null,{
      validators:[Validators.required]
    }),
    leadType: new FormControl(null,{
      validators:[Validators.required]
    }),
    keywords: new FormControl(null, {
      validators: [Validators.required, Validators.minLength(3)]
    }),
   
  });
}

CodePudding user response:

  1. Declare a flag (isSubmitted) to record whether the form is submitted.
isSubmitted: boolean = false;
  1. Add submit event to update isSubmitted to true when the submit button is clicked.
<form [formGroup]="form" (submit)="isSubmitted = true">
  ...
</form>
  1. Show the error message when isSubmitted is true and FormControl fails the validation.
<mat-error *ngIf="isSubmitted && form.get('visibility').invalid">
  Please select channel visibility.
</mat-error>

Demo @ StackBlitz

CodePudding user response:

Not sure this helps. try touched like this

<mat-error *ngIf="form.get('visibility').invalid && form.get('visibility').touched">
    Please select channel visibility.
</mat-error>

CodePudding user response:

A mat-error is showed by defect if the "formControl" is invalid and touched. So, generally you can use markAsTouched when submit

  submit(form: FormGroup) {
    if (form.valid) {
      ..do something...
    } else form.markAllAsTouched();
  }

A little example in the stackblitz

  • Related