How to validate checkbox form in angular 15

37 Views Asked by At

I have six checkbox. Need to validate the form Atleast select any one checkbox. When i click the submit button i want to validate the form. How to do it in angular 15.

Demo: https://stackblitz.com/edit/angular-gitter-xpfw5z?file=app%2Fapp.component.html

app.component.html:

    <div style="padding: 1rem">
    <form [formGroup]="formGroup">
    <div>
      <ul>
         <li><label><input type="checkbox"  formControlName="chklist"/> First Chk box  </label></li>
         <li><label><input type="checkbox"  formControlName="chklist"/> Second Chk box  </label></li>
         <li><label><input type="checkbox"  formControlName="chklist"/> Third Chk box  </label></li>
         <li><label><input type="checkbox"  formControlName="chklist"/> Fourth Chk box  </label></li>
         <li><label><input type="checkbox"  formControlName="chklist"/> Five Chk box  </label></li>
         <li><label><input type="checkbox"  formControlName="chklist"/> Six Chk box  </label></li>
      </ul>
    </div>
    <div style="color: red; padding-top: 0.2rem">
      Atleast select one checkbox
    </div>
    <hr />
    <div>
      <button type="submit" (click)="formSubmit()">Submit</button>
    </div>
    </form>
    </div>

app.component.ts:

 ngOnInit(): void {
   this.formGroup = this.formBuilder.group({
  chklist: ['', Validators.required],
  });
  }

formSubmit(){
if(this.formGroup.valid){
  alert("Form is valid")
}else{alert("Form not valid");
}
0

There are 0 best solutions below