Since there is no elegant solution to this, I have bitten the bullet to write my own RequiredIf validator.
It does two things:
- cache the original validators of the controls it is applied to. Should a property no longer be required, it will restore the original validators (while removing the required validator).
- it adds valueChange listeners on the property, the validation depends on. If a property becomes required or is no longer required, it will validate the control to immediately show the new validation results.
Here's my code of the validator (just as I use it currently, no time to optimize it).
import { FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { Subscription } from 'rxjs';
export class ValidationSubscriptionCache {
static observedPropertyCombinations = new Array<string>();
static subscriptions = new Array<Subscription>();
static unsubscribeAll() {
for (let subscription of ValidationSubscriptionCache.subscriptions) {
subscription.unsubscribe();
}
}
}
export function CombineProperties(property: string, otherProperty: string) {
return `${ property }.${ otherProperty }`;
}
export class ValidatorCache {
static cache = new Array<ValidatorsOfProperty>();
static currentlyRequiredProperties = new Array<string>();
static isCurrentlyRequired(property: string) {
return ValidatorCache.currentlyRequiredProperties.indexOf(property) > -1;
}
static removeFromCurrentlyRequiredProperties(property: string) {
const index = ValidatorCache.currentlyRequiredProperties.indexOf(property, 0);
if (index > -1) {
ValidatorCache.currentlyRequiredProperties.splice(index, 1);
}
}
static isInCache(property: string) {
const found = this.cache.find(x => x.property === property);
if (found) {
return true;
}
return false;
}
static addToCache(property: string, validators: any) {
const toAdd = new ValidatorsOfProperty();
toAdd.property = property;
toAdd.validators = validators;
ValidatorCache.cache.push(toAdd);
}
static popFromCache(property: string): ValidatorsOfProperty {
const item = ValidatorCache.cache.find(x => x.property === property);
const index = ValidatorCache.cache.indexOf(item, 0);
ValidatorCache.cache.splice(index, 1);
return item;
}
}
export class ValidatorsOfProperty {
property: string;
validators: any;
}
export function ValidateRequiredIf(property: string, otherProperty: string, valueThatMakesRequired) {
return (formGroup: FormGroup): ValidationErrors | null => {
const propertyCombination = CombineProperties(property, otherProperty);
const otherValue = formGroup.get(otherProperty).value;
//register changes of other property and refresh validation if it changes
if (ValidationSubscriptionCache.observedPropertyCombinations.indexOf(propertyCombination) < 0) {
ValidationSubscriptionCache.observedPropertyCombinations.push(propertyCombination);
const valueChangeSubscription =
formGroup.get(otherProperty).valueChanges
.subscribe(() => {
formGroup.get(property).markAsTouched();
formGroup.get(property).updateValueAndValidity();
});
ValidationSubscriptionCache.subscriptions.push(valueChangeSubscription);
}
//set or remove the required validator based on the depending property
const isRequired =
otherValue !== null &&
otherValue !== undefined &&
otherValue.toString() === valueThatMakesRequired.toString();
if (isRequired && !ValidatorCache.isCurrentlyRequired(property)) {
ValidatorCache.currentlyRequiredProperties.push(property);
ValidatorCache.addToCache(property, formGroup.get(property).validator);
if (formGroup.get(property).validator) {
formGroup.get(property).setValidators([ formGroup.get(property).validator, Validators.required ]);
} else {
formGroup.get(property).setValidators(Validators.required);
}
}
if (!isRequired && ValidatorCache.isCurrentlyRequired(property)) {
ValidatorCache.removeFromCurrentlyRequiredProperties(property);
formGroup.get(property).setValidators(ValidatorCache.popFromCache(property).validators);
}
return null;
};
}
And here's the application on the form:
this.myForm.setValidators(
[
//city is required if the country is switzerland
ValidateRequiredIf('city', 'nationality', 'switzerland'),
//[add more]
]);
additionally, you have to call ValidationSubscriptionCache.unsubscribeAll(); in the ngOnDestroy() of your component holding the form.
Cheers, Mike
AbstractControlonly, because in my code, validators are added in different locations from different sources. E.g. validators are added asynchronously based on a loaded json schema of the business object, other validators are added dynamically and custom validators are added manually on the form. So, keeping track of all these sources is practically impossible. Angular letting me down here... - MikeJ82