Home > Blockchain >  How to validate gender (radio button) in angular
How to validate gender (radio button) in angular

Time:10-13

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 >
         <input type="radio" id="female" value="F" name="gender" required>
   <label for="female">Female</label>
       </div>
        
         <div >
           <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>

CodePudding user response:

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

  • Related