Shawn
Shawn

Reputation: 71

angular2 validation: finding current validators on a control

Angular RC4 How to add and remove Validation based on the state of other FormControls or FormGroups.

Based on this post Angular2 validator which relies on multiple form fields

In the example- It uses .compose to set multiple validators. It replaces the existing Validators with you new Validator.compose

this.form.controls["empID"].validator = Validators.compose([Validators.pattern("[0-9]{7}"), Validators.required]);
this.form.controls["empID"].updateValueAndValidity();

My issues is I can't find FormControl (.add or .remove) to change the current validation (one Validator at a time). If I want to add/remove Validators.required I would have to pull the current validators (another issue) and then add/remove require in the new .compose. (example above)

Am I overthinking this process. To add a validator dynamically works but only if I know all the validators.

One last thing I am try to make this generic by passing a control in and evaluate if another control is checked then apply/remove Validators accordingly.

Upvotes: 6

Views: 691

Answers (1)

Lucas Moulin
Lucas Moulin

Reputation: 2530

Per Angular's documentation this isn't possible. On the AbstractControl documentation (which is the class that FormControl extends) there is no member to retrieve the current validators.

Unfortunately your only option is to use the two methods available to deal with validators:

setValidators() // Replaces all validators
clearValidators() // Removes all validators

Upvotes: 0

Related Questions