0

I have a form element as follows:

<input type="text" id="country" formControlName="Country" />

I have form group as follows:

 this.myForm = this.formbuilder.group({
            'Country': [{ value: this.user.Country, disabled: this.SomeProperty===true}, [Validators.required]],
});

When it is disabled when this.SomeProperty is true, required validator does not work at all and Save button is enabled.

<button type="submit" [disabled]="!myForm.valid">Save</button>

Is there anyway to force validation for disabled attribute?

The reason the required property can be null is because of some data issue or data got migrated from different source without the required values which is beyond my control.

ANewGuyInTown
  • 5,957
  • 5
  • 33
  • 45
  • you can call function like this: [disabled]="validationFunction()" and return true and false based on different cases – Amrit Apr 05 '19 at 05:05
  • not disable the FormControl, use [attr.disabled]="condition" (this disabled the input but not disabled the FormControl) – Eliseo Apr 08 '19 at 06:47

1 Answers1

2

Hmmm.. Generally, Angular Reactive Forms will not trigger validators for disabled form fields.

I can suggest two ways for you to get around this situation:

1) Writing a custom validator on your FormGroup to manually check the values for each individual Form Control.

this.myForm = this.formbuilder.group({
  'Country': [{ value: this.user.Country, disabled: this.SomeProperty===true}, [Validators.required]],
   // other FormControls
}, { validator: GroupValidator.checkEveryField() });

Then, create a new Validator class that checks for an empty Country FormControl. If it is empty, it will return the validation error.

import { AbstractControl } from '@angular/forms';

export class GroupValidator {

  static checkEveryField(control: AbstractControl) {
    const { Country } = control.value;
    if (!Country) {
      return { 'invalidCountry': true };
    } else {
      return null;
    }
  }
}

2) Writing a method that checks the values of the incoming data before you patch the values to your FormGroup.

this.someService.getData().subscribe(response => {
  if (!response.user.Country) {
    // trigger invalid validation response
  } else {
    this.myForm.patchVaue(response.user);
  }
});
wentjun
  • 40,384
  • 10
  • 95
  • 107
  • control does not contain disabled fields, so `const { Country } = control.value` always return null. We should use `const { Country } = (control as FormGroup).getRawValue()` instead. – TlmaK0 Jun 29 '23 at 06:27