0

How to check validation dynamic checkbox is checked or not. formgroup validation not working.

html=>

<div class="col-md-6">
    <div class="form-group">
        <label for="date2">Keywords</label>
        <ul class="keywords-ul">
            <li *ngFor="let keyword of keyWordsArr">
                <input type="checkbox" id="{{keyword}}" required (change)="getFinalKeywords($event.target.value)" value="{{keyword}}" formControlName="keywords" class="form-control" [required] [ngClass]="{ 'is-invalid': submitted && f.keywords.errors }">
                <label for="{{keyword}}">{{keyword}}</label>
            </li>
            <div *ngIf="myForm.get('keywords').errors  && submitted">
                <div *ngIf="myForm.get('keywords').hasError('required')">
                    <span style="color: red;">Please select keywords
                                                            Name.</span>
                </div>
            </div>
        </ul>
    </div>
</div>

t.s file=>

this.myForm = this._formBuilder.group({
      //from validation of contact details...
      company_name: new FormControl('', [  
        Validators.required,  
        Validators.minLength(3),  
        Validators.maxLength(30),  
        Validators.pattern('^[a-zA-Z ]*$')]), 
      emailId:new FormControl('', [  
        Validators.required,  
        Validators.minLength(20),  
        Validators.maxLength(30),  
        Validators.pattern("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$")  
      ]),  
      owner_name:new FormControl('', [  
        Validators.required,  
        Validators.minLength(3),  
        Validators.maxLength(30),  
        Validators.pattern('^[a-zA-Z ]*$')]), 
      mobNo: new FormControl('', [  
        Validators.required,  
        Validators.minLength(10),  
        Validators.maxLength(12),  
        Validators.pattern('^[0-9]*$')]), 
      state: new FormControl('', []), 
      city:new FormControl('', []),
      category:new FormControl('', []),
      sub_category: new FormControl('', []),
      sub_sub_category: new FormControl('', []),
      keywords: new FormControl('', []),
    });
theduck
  • 2,589
  • 13
  • 17
  • 23
  • 1. If you're going with model-driven forms, then remove validation (that `required` attribute) from the template. 2. What is your desired outcome, at least one of checkboxes being required? You can check this thread: https://stackoverflow.com/questions/40321033/angular2-formbuilder-validatiors-require-at-least-one-field-in-a-group-to-be-fi – mbojko Oct 10 '19 at 13:25
  • 1
    a validation of checkbox is `Validators.requiredTrue`, see https://angular.io/api/forms/Validators – Eliseo Oct 10 '19 at 21:14

0 Answers0