Validation not working for checkbox.
When checkbox is not selected, form is getting submitted. Also not showing error.
HTML Code
<form [formGroup]="feedbackFormWithArray" (ngSubmit)="submitData()">
<label class="form-control-label"><span class="text-danger">*</span>Recommendation:</label>
<div class="recommendation-div">
<div class="rec-div" *ngFor="let recommendation of recommendations">
<label class="container">{{recommendation.listTypeValueName}}
<input formControlName="recommendation" type="checkbox" value="{{recommendation.listTypeValueId}}"
[checked]="recommendation.selected" (change)="isAllSelected(recommendation)" />
<span class="mark"></span>
</label>
<div *ngIf="(submitted && recommendation.invalid)">
<small *ngIf="recommendation.errors?.required" class="text-danger">Please select recommendation</small>
</div>
</div>
</div>
</form>
TS Code
import { Validators } from '@angular/forms';
submitted : boolean = false;
this.feedbackFormWithArray= this.fb.group({
recommendation: ['', [Validators.required]]
});
submitData() {
this.submitted = true;
}
get recommendation()
{
return this.feedbackFormWithArray.get('recommendation');
}
How to solve this?
Thank you!
3
Answers
I think replace feedbackForm with feedbackFormWithArray in 3 rd line of ts code
There is a static property in class Validators called "requiredTrue".
@description
Validator that requires the control’s value be true. This validator is commonly used for required checkboxes.
You can check more about it here https://angular.io/api/forms/Validators