Skip to content

Instantly share code, notes, and snippets.

@ganqqwerty
Last active June 19, 2019 07:07
Show Gist options
  • Save ganqqwerty/c0702123aec09fc9164fb245f07b65b2 to your computer and use it in GitHub Desktop.
Save ganqqwerty/c0702123aec09fc9164fb245f07b65b2 to your computer and use it in GitHub Desktop.
/**
* makes the field required if the predicate function returns true
*/
function requiredIfValidator(predicate) {
return (formControl => {
if (!formControl.parent) {
return null;
}
if (predicate()) {
return Validators.required(formControl);
}
return null;
})
}
//in ngOnInit:
this.myForm = this.fb.group({
myCheckbox: [''],
myEmailField: ['', [
Validators.maxLength(250),
Validators.minLength(5),
Validators.pattern(/.+@.+\..+/),
// <--- here we pass predicate arrow function
requiredIfValidator(() => this.myForm.get('myCheckbox').value)
]]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment