Last active
June 19, 2019 07:07
-
-
Save ganqqwerty/c0702123aec09fc9164fb245f07b65b2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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