Is there a way to dynamically require a form field based on conditions? I created a custom validator, but the conditional variables passed to it remain static. How can I update these conditional values within the custom validator function? Is it possible to achieve this using Validators.required
instead of a custom validator?
private foo: boolean = false;
private bar: boolean = true;
constructor(private _fb: FormBuilder) {
function conditionalRequired(...conditions: boolean[]) {
return (control: Control): { [s: string]: boolean } => {
let required: boolean = true;
for (var i = 0; i < conditions.length; i++) {
if (conditions[i] === false) {
required = false;
}
}
if (required && !control.value) {
return { required: true }
}
}
}
this.applyForm = _fb.group({
'firstName': ['', Validators.compose([
conditionalRequired(this.foo, !this.bar)
])],
...
});
}
Update (May 17, 2016)
It has been quite some time since I posted this query. I would like to mention the .include()
and .exclude()
methods provided by the ControlGroup
class for those looking to implement similar functionality. (docs) While a conditional Validator may have its use cases, I have found that including and excluding controls, control groups, and control arrays is an effective approach. Simply apply the required
validator to the desired control and manage its inclusion/exclusion accordingly. Hopefully, this information proves helpful to someone!