skip to Main Content

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


  1. I think replace feedbackForm with feedbackFormWithArray in 3 rd line of ts code

    Login or Signup to reply.
  2. import { Validators } from '@angular/forms';
    
    submitted : boolean  = false;
    //in reactive form you should take care the form controller's name.
    this.feedbackFormWithArray= this.fb.group({
      recommendation: ['', [Validators.required]]
    });
    
    submitData() {
      this.submitted = true;
    }
    
    get recommendation()
    {
      return this.feedbackFormWithArray.get('recommendation');
    }
    
    Login or Signup to reply.
  3. There is a static property in class Validators called "requiredTrue".

    this.feedbackFormWithArray= this.fb.group({
        recommendation: ['', [Validators.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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search