2

I am working on a requirement where the user needs to select at least one value to get the result.

Here is my component.ts file

  initializeForm():void{
this.myForm= this.frmBuilder.group({
  field1: [null],
  field2: [null],
  field3: [null] )
}, this.AtLeastOneInputHasValue1);
 }



 AtLeastOneInputHasValue1=(validator: ValidatorFn) => (
  group: FormGroup,
  ): ValidationErrors | null => {
 const hasAtLeastOne =
  group &&
  group.controls &&
  Object.keys(group.controls).some(k => !validator(group.controls[k]));

return hasAtLeastOne ? null : { atLeastOne: true };
};



get frm(): any {
return this.myForm.controls;
 }

component.html

<form *ngIf="myForm" [formGroup]="myForm">

<div class="row">
    <div class="col-md-2">
        <label>Field1</label>
        <p-autoComplete [(ngModel)]="Field1Model"  field="Field1" formControlName="Field1"
            (onSelect)="doSomething()"  [multiple]="true">
        </p-autoComplete>
        <div *ngIf="frm.Field1.invalid && (frm.Field1.dirty || frm.Field1.touched)" class="text-danger">
            <div *ngIf="frm.Field1.errors.required">Field1 is required</div>
        </div>
    </div>
    <div class="col-md-2">
        <label>Field2</label> 
        <p-multiSelect [options]="Field2Options" [(ngModel)]="Field2Model"  formControlName="courseName"
        defaultLabel="Select a Field" optionLabel="Field2Name">
    </p-multiSelect>
    <div *ngIf="frm.Field2.invalid && (frm.Field2.dirty || frm.Field2.touched)" class="text-danger">
        <div *ngIf="frm.Field2.errors.required">Field2 is required</div>
    </div>
    </div>
    <div class="col-md-2">
        <label>Field3 </label> 
        <p-multiSelect [options]="Field3List" [(ngModel)]="Field3Model" formControlName="Field3"  
        defaultLabel="Select a status" optionLabel="statusName">
    </p-multiSelect>
    <div *ngIf="frm.Field3.invalid && (frm.Field3.dirty || frm.Field3.touched)" class="text-danger">
        <div *ngIf="frm.Field3.errors.required">Field3 is required</div>
    </div>
    </div>
     
     
     
    <div class="col-md-2">
        <div class="row" style="padding-top: 27px;">
            <button pButton type="button" label="Search" [disabled]='!myForm.valid'
                class="d-inline-block mb-2 pb-1" (click)="SearchFilter()"></button>
        </div>
    </div>
</div>

It is not working. If I use Validators.required in any of the fields then it shows a message under that control, but I want to use that at least one field should be selected to get the result.

I followed reference Angular2 FormBuilder Validators: require at least one field in a group to be filled but its not working.

What I missed. Thank you in advance.

Virender Thakur
  • 327
  • 3
  • 12

0 Answers0