noclist
noclist

Reputation: 1819

Dynamic validation in Angular reactive forms

I have a reactive form in Angular. How can I perform a required validation on tax only if openDate and closeDate have been populated?

this.employerBasicsForm = this.fb.group({
  tax: ['', [Validators.required],
  openDate: [''],
  closeDate: [''],
});

Upvotes: 0

Views: 5043

Answers (3)

Eliseo
Eliseo

Reputation: 58099

Andrew some like

  employerBasicsForm = new FormGroup(
    {
      tax: new FormControl(),
      openDate: new FormControl(),
      closeDate: new FormControl()
    },
    this.validationTax()
  );

  validationTax() {
    return (group: FormGroup) => {
      return group.value.openDate && group.value.closeDate && !group.value.tax
        ? { required: true }
        : null;
    };
  }

Are not very complex. For me it's the best solution, but I also respect your opinion. Well, in this case I use a function in the own component because this validator are not used never outside the component

Upvotes: 1

Andrew Howard
Andrew Howard

Reputation: 3092

Here is the answer, no custom validator required in this case:

Make your form normally without validator to begin with:

this.employerBasicsForm = this.fb.group({
  tax: [''],
  openDate: [''],
  closeDate: [''],
});

A change method is required on both your openDate and closeDate fields:

<div><input type="text" formControlName="openDate" (change)="checkFields()" /></div>
<div><input type="text" formControlName="closeDate" (change)="checkFields()" /></div>

Then in your checkFields method:

checkFields() {

// Clear the validator every time a change occurs
this.employerBasicsForm.controls.tax.clearValidators();

// If both fields have been filled in, then make tax required
if ((this.employerBasicsForm.controls.openDate.value != null && this.employerBasicsForm.controls.closeDate.value != null))
{
  this.employerBasicsForm.controls.tax.setValidators([Validators.required]);
}

// Update the validity
this.employerBasicsForm.controls.tax.updateValueAndValidity();
}

Upvotes: 0

StephenHealey86
StephenHealey86

Reputation: 81

Write your own ValidatorFn. You can use it in the form group and access the form controls to check their state or use it on the form control itself and access the sibling controls through the form control parent property.

https://angular.io/api/forms/ValidatorFn

Upvotes: 0

Related Questions