Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to validate gender (radio button) in angular

How can I validate if gender was selected in angular, also I want the warning message to disappear once I select male or female.
I tried the code below but it works for inputs field such name or email
but for radio button it shows the error message even if I selected one option
enter image description here

  this.registerForm = this._formBuilder.group({
 gender: ['', Validators.required]
   });

onSubmit() {
 this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
  return;
   }
 }

HTML

 <form  [formGroup]="registerForm" (ngSubmit)="onSubmit()">
     <div class="custom-control custom-radio">
         <input type="radio" id="female" value="F" name="gender" required>
   <label for="female">Female</label>
       </div>
        
         <div class="custom-control custom-radio">
           <input type="radio" id="male" value="M" name="gender"required>
           <label for="male">Male</label>
         </div>

         <div *ngIf="submitted && f.gender.errors" 
         [ngClass]="{ 'd-block': submitted && f.gender.errors }">
         <div *ngIf="f.gender.errors.required">Gender is required</div>
       </div>
   
 <button>Sign up</button>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You forgot to bind the inputs to the FormControl. Add formControlName="gender" to both inputs and it should work.

<form  [formGroup]="registerForm" (ngSubmit)="onSubmit()">
  ...
     <input type="radio" id="female" value="F" name="gender" formControlName="gender">
  ...
     <input type="radio" id="male" value="M" name="gender" formControlName="gender">
  ...

Cheers

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading