How should I go about conditionally requiring a form field? I made a custom validator, but the conditional variables that I pass to the custom validator are static and remain their initial values. What should my custom validator look like to get updated conditional values? Perhaps there is a way to do this with 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's been a long time since posting this, but I'd like to reference the .include() and .exclude() methods available on the ControlGroup class for anyone out there who is trying to create this functionality. (docs) While there are probably use cases for a conditional Validator like above, I've found the inclusion and exclusion of controls, control groups, and control arrays to be a great way to handle this. Just set the required validator on the control you'd like and include/exclude it as you please. Hope this helps someone!