Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 476
Furqan S. Mahmoud Avatar asked Jul 28 '18 17:07

Furqan S. Mahmoud


1 Answers

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;
}
like image 87
Frederik Prijck Avatar answered Oct 10 '22 06:10

Frederik Prijck