Furqan S. Mahmoud
Furqan S. Mahmoud

Reputation: 1465

How to validate disabled control using reactive forms (validation is not triggered)

Let's say that I have this form structure:

      this.entryForm = this.formBuilder.group({
            date: [{value:'' , disabled: true}, [Validators.required]],
            notes: [''],
            sum_credit: [{value:'', disabled: true }],   
            sum_debit: [{value:'', disabled: true}],
            items: this.initItems()
          });
// set validation function to sum_credit

   this.entryForm.controls['sum_credit'].setValidators([CommonValidations.validateSomthing(...)]);

The sum_credit is disabled because it's value is always calculated. Now I need to validate that the sum_credit is equaled to sum_debit, and I'm already doing that using validateSomthing function. The problem is that the validateSomthing is not triggered because the control is disabled. How can I fix that?

Thanks

Upvotes: 8

Views: 26272

Answers (1)

Frederik Prijck
Frederik Prijck

Reputation: 1509

Angular doesn't trigger validators for disabled fields. One way to work around this is to apply the validator to the group instead of the control (this will trigger the validator for each update to any, none disabled, form control inside the correspondig group:

this.entryForm = this.formBuilder.group({
    date: [{value:'' , disabled: true}, [Validators.required]],
    notes: [''],
    sum_credit: [{value:'', disabled: true }],   
    sum_debit: [{value:'', disabled: true}],
    items: this.initItems()
  }, { validator: CommonValidations.validateSomthing(...) });

Note that you need to adapt your validator function to read the value from the sum_debit control:

validateFn(group: AbstractControl) {
  const control = group.get('sum_debit');
  // here you can validate control.value;
}

Upvotes: 17

Related Questions