Olivier
Olivier

Reputation: 445

Custom validator on FormGroup isn't called

I created a custom validator that I integrated into a FormGroup like this:

  private createOrder(): FormGroup {
    return new FormGroup(
      {
        produit: new FormControl(['', Validators.required]),
        document: new FormControl(['', Validators.required]),
        quantite: new FormControl(['', Validators.required])
      },
      { validators: this.validateQuantity });
  }

  protected addOrder(): void {
    this.ordersFormArray.push(this.createOrder());
  }

Here's the validator:

  validateQuantity() {
    return (formFroup: FormGroup) => {
      const produitLabel = formFroup.get('produit')?.value;
      if (!produitLabel) return null;

      const documentLabel = formFroup.get('document')?.value;
      if (!documentLabel) return null;

      const quantite = formFroup.get('quantite')?.value;
      if (!quantite) return null;

      const produit = this.productList.find((v) => v.label === produitLabel);

      const document = produit?.documents.find(
        (v) => v.label === documentLabel
      );

      if (!document?.qtteMax) return null;

      if (document.qtteMax < quantite) {
        return {
          validateQuantity: {
            max: document.qtteMax,
            actual: quantite,
            documentLabel
          }
        };
      }
      return null;
    };
  }

And the HTML:

    <mat-error
      *ngIf="ordersFormArray.controls[i]?.hasError('validateQuantity')">
      {{ 'order.form.message.documentsAuthorizedQuantityError' | translate: {
      maxQuantity: ordersFormArray.controls[i].getError('validateQuantity').max,
      documentLabel: ordersFormArray.controls[i].getError('validateQuantity').documentLabel
    } }}
    </mat-error>

when I create the form using the FormBuilder, the validator is correctly called but I don't understand why the validator isn't correctly called when I use the FormFroup with FormControls, thanks for help

when I create the form using the FormBuilder, the validator is correctly called but I know that the FormBuilder is now deprecated I don't understand why the validator isn't correctly called when I use the FormFroup with FormControls,

The validator is correctly called with this code...

 private createOrder(): FormGroup {
    return this.formBuilder.group(
      {
        produit: ['', Validators.required],
        document: ['', Validators.required],
        quantite: ['', Validators.required]
      },
      {
        validator: this.validateQuantity()
      }
    );
  }

Thanks for help

Upvotes: 0

Views: 39

Answers (0)

Related Questions