Search code examples
angularformsform-controlformgroups

At Least One Control of FormGourp is valid to enable submit form


I have Two controls on my FormGroup I need at least one of two controls be validate to make possible submitting form

I need that formGroup valid if only one FormControl is valid

this.form = this.fb.group({
        'keyWord' : new FormControl(null, [
          Validators.required,
          Validators.minLength(4)
        ]),
        'name':  new FormControl(null, [
          Validators.required
 ])

      });

html

 <form [formGroup]="form" (ngSubmit)="isPending=!isPending;searchCriteria(form.value);" class="form-group" novalidate>
        <small class="text-danger" *ngIf="?????">At Least One Field is required</small>
        <div class="input-group box-shadow">
            <div class="input-group-addon border-top-0 border-left-0 border-bottom-0 rounded-0">
                <i class="fa fa-search"></i>
            </div>
            <input type="text" formControlName="keyWord" placeholder="" class="form-control border-0">
            <input type="text" formControlName="name" placeholder="" class="form-control border-0">
            <button type="submit" value="submit">
      </form>

Solution

  • You can try this

    <form [formGroup]="form" (ngSubmit)="isPending=!isPending;searchCriteria(form.value);" class="form-group" novalidate>
                <small class="text-danger" *ngIf="?????">At Least One Field is required</small>
                <div class="input-group box-shadow">
                    <div class="input-group-addon border-top-0 border-left-0 border-bottom-0 rounded-0">
                        <i class="fa fa-search"></i>
                    </div>
                    <input type="text" formControlName="keyWord" placeholder="" class="form-control border-0">
                    <input type="text" formControlName="name" placeholder="" class="form-control border-0">
                    <button type="submit" value="submit" [disabled]="isvalid()">
              </form>
    

    component function

      isValid(): boolean {
             if(this.form.get('keyWord').valid ||this.form.get('name').valid){
                retrun false;
             }
          return true;
        }