I am trying to show validation error message for angular for. I have three checkboxes. If i not selected anyone i want to show error message. How to do it in reactive form validation in angular.
Demo: https://stackblitz.com/edit/angular-gitter-ddqhne?file=app%2Fapp.component.html
app.component.html:
<form [formGroup]="formGroup">
<label *ngFor="let val of data"><input type="checkbox" name="val.name" id="val.id" formControlName="cb"> {{val.value}}</label>
<div style="color: red; padding-top: 0.2rem">
Atleast select one checkbox
</div>
<hr>
<div>
<button type="submit">Submit</button>
</div>
</form>
app.component.ts:
ngOnInit(): void {
this.formGroup = this.formBuilder.group({
cb: [false, Validators.requiredTrue]
});
}
Updated my answer to use
formControlNamethe remaining explanation stays the same! But I use.bind(this, data)to pass the data that is used on the*ngForto initialize the checkboxes, because the data is dynamic, so we need to pass the original data to ensure the values are checked so that atleast once checkbox is checked!validator
stackblitz demo
We can use a
formArrayfor the checkboxes this will ensure the inputs are under the same formArray controlWe need a custom validator to check if any of the checkboxes are checked, we use the below code for that
validator function
On the html side, we group all the checkboxes under one
formGroupName, then assign the formArray controls to the checkboxes. Then we can check if the error exists by doing*ngIf="formGroup?.errors?.checkboxSectionValid"on the error message div!full code
html
stackblitz demo