Skip to content

FormControl.setValidators...why is there no getValidators? #13461

@Icepick

Description

@Icepick

I'm submitting a ... (check one with "x")

[ ] bug report => search github for a similar issue or PR before submitting
[x] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior
We have an AbstractControl with basic validators like (required, maxLength) in a ReactiveForm via TypeScript FormBuilder. To those basic validators we added a custom validator which dynamically change the validation strategy based on a dropdown value. Currently we are using the setValidators() method inside another component (AbstractControl is included via @Input()). The main problem is that it overwrites existing validators.
Example:

App Component

this.formBuilder.group({
      zip: ['', [Validators.required, Validators.maxLength(10)]] 
    });

App Template

<zip ...
        [control]="form.controls.zip">
</zip>

ZIP Component

@Input() control: AbstractControl;

this.control.setValidators([
      // redundant to formBuilder
      Validators.required,
      Validators.maxLength(10),
      // custom validation based on a dropdown value (via. valueChange Detection)
      validateZipFn(countryCode)]
    );

Expected behavior
To stay flexible we don't want to overwrite all validators. The below code would illustrate the behavior with a getValidators() method.

App Component

this.formBuilder.group({
      zip: ['', [Validators.required, Validators.maxLength(10)]]
    });

App Template

<zip ...
        [control]="form.controls.zip">
</zip>

ZIP Component

@Input() control: AbstractControl;

let listOfAllValidationRules = this.control.getValidators().push(validateZipFn(countryCode)]);
this.control.setValidators(listOfAllValidationRules);

What is the motivation / use case for changing the behavior?
Being more flexible with dynamic validation.

  • Angular version: ~2.1.2

  • Browser: all

  • Language: TypeScript / ES6

Metadata

Metadata

Assignees

Labels

area: formsfeatureIssue that requests a new featurefeature: under considerationFeature request for which voting has completed and the request is now under considerationfreq2: medium

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions