In Angular 4 app I have a form model like this:
this.form = this._fb.group({
title: [\'\', [Validators.required, Validators.minLength(3), Validators.maxLengt
I don't like clearing and setting validators, as I have to repeat all static validators (patterns, min, max, etc.) just to have a dynamic "required" validator.
I use a conditional validator:
export function conditionalValidator(condFn: (control: AbstractControl) => boolean,
validators: ValidatorFn | ValidatorFn[]): ValidatorFn {
return (control) => {
if (!condFn(control)) {
return null;
}
if (!Array.isArray(validators)) {
return validators(control);
}
return validators.map(v => v(control)).reduce((errors, result) =>
result === null ? errors :
(Object.assign(errors || {}, result))
);
};
}
I can then mix a static validator with a dynamic "required" condition:
this.fb.group({name: ['', [Validators.minLength(4),
conditionalValidator(this.isClientProj, Validators.required)]]}
Where isClientProj()
is the condition function (closure)