FormGroup validator

Viewed 1373

How can I add validator to formgroup that contains formcontrols.

I have this.

users.forEach(e => {
  console.log(e);
  this.filasValidator.push(new FormGroup({
      dia: new FormControl('0')
  },
    [Validators.required, Validators.min(1)]
  ));
});
console.log(this.filasValidator.controls[0].invalid);

FilasValidator is a FormArray

in template html i have this

  <ng-template formArrayName="filas"
               #inputTemplate
               let-value="value"
               let-row="row"
               let-column="column"
               let-rowIndex="rowIndex">
    <label [formGroupName]="rowIndex" class="pya-cell">
      <small class="text-muted d-block d-lg-none">{{ column.name }}</small>
      <!--REVISAR VALUE, DA ERROR DE REASIGNACION -->
      <input
        (input)="editHour(rowIndex, column.prop, $event)"
        formControlName="dia"
        [ngClass]="{'is-invalid': filasValidator.controls[rowIndex].invalid}"
        type="number"
        value="{{ value }}"
        class="number text-center w-50 form-control light"
      />
    </label>
  </ng-template>

It is difficult to explain, but look I have a table, in which there are several days of the week, to those days I must put a formcontrol, but the row must be valid if at least 1 record is greater than 0. That is why I need the validation to be outside the formcontrols

I tried this

  this.filasValidator.push(new FormGroup({
      lunes: new FormControl('0', Validators.min(1)),
      martes: new FormControl('0', Validators.min(1)),
      miercoles: new FormControl('0', Validators.min(1)),
      jueves: new FormControl('0', Validators.min(1)),
      viernes: new FormControl('0', Validators.min(1))
  },
    [Validators.required]
  ));

But i need Validators.min outside the FormControls.

1 Answers

Edit:

I did this change, making a custom validator and putting in the FormGroup to validate all fields

Stackblitz

export class OpponentDetailsComponent implements OnInit {
      objFormGroup = this.formBuilder.group(
        {
          test: [null],
          test2: [null]
        },
        { validators: [this.validatorArray()] }
      );

      constructor(private formBuilder: FormBuilder) {}

      ngOnInit(): void {}

     validatorArray(): ValidatorFn {
        return (group: FormGroup) => {
          for (let key of Object.keys(group.controls)) {
           if (group.controls[key].value > 0) return null;
        }

        return { min: 1 }
      };
   }
}

Original answer:

You can put a validator in your FormGroup the same way that you put in your FormControl, like this:

new FormGroup({dia: new FormControl('0')}, [Validators.required])
Related