6

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.

1 Answer 1

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.