Validate radio button group before submit - Angular Reactive Forms

Viewed 68

I would like to validate the radio buttons before the form is submitted because my submit button is disabled untill all the fields are valid. All the examples I've seen of radio button validation do not include disabling the submit button.

Is it that I will have to change the way I validate all the other form fields to accommodate the validation of the radio button? Can it be validated without first submitting the form?

contact.component.html

<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">

    <mat-label>Name</mat-label>
    <mat-form-field floatLabel="never" [hideRequiredMarker]="true">
        <input type="text" matInput formControlName="name" placeholder="Your name"
            [required]="true">
    </mat-form-field>
    <mat-error *ngIf="contactForm.get('name')?.invalid && contactForm.get('name')?.touched">
        Please enter your name
    </mat-error>

    <mat-label id="help-options">How can we help you?</mat-label>
    <mat-radio-group aria-labelledby="help-options" [required]="true" formControlName="request">
        <mat-radio-button *ngFor="let option of requestOptions" [value]="option.val">
            {{option.req}}
        </mat-radio-button>
    </mat-radio-group>
    <mat-error *ngIf="isFormSubmitted && contactForm.get('request')?.errors?.['required']">
        Please select an option from the list above
    </mat-error>

    <div>
        <button type="submit" [disabled]="!contactForm.valid" mat-button ngClass="w-100 button btn-dark-blue-2">Send
            message</button>
    </div>
</form>

contact.component.ts

 import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
    import { Component, OnInit, Renderer2 } from '@angular/core';
    
    
    @Component({
      selector: 'app-contact-us',
      templateUrl: './contact-us.component.html',
      styleUrls: ['./contact-us.component.scss']
    })
    export class ContactUsComponent implements OnInit {
    
      contactForm: FormGroup
      isFormSubmitted = false;
    
      requestOptions = [
        { val: '1', req: 'Option 1' },
        { val: '2', req: 'Option 2' },
        { val: '3', req: 'Option 3' }
      ];
    
      constructor(
        private renderer: Renderer2,
        private fb: FormBuilder
      ) {
    
        this.contactForm = this.fb.group({
          name: new FormControl('', Validators.required),
          request: new FormControl('', Validators.required)
        })
      }
    
      ngOnInit(): void {
      }
    
      onSubmit() {
    
        this.isFormSubmitted = true;
    
        if (!this.contactForm) {
          return false;
        }
        else {
          console.log(this.contactForm.value);
          return true;
        }
      }
    
    }
0 Answers
Related