Skip to content

Instantly share code, notes, and snippets.

@ganqqwerty
Last active June 19, 2019 13:52
Show Gist options
  • Save ganqqwerty/68908af0ec820862247cefca9ff40036 to your computer and use it in GitHub Desktop.
Save ganqqwerty/68908af0ec820862247cefca9ff40036 to your computer and use it in GitHub Desktop.
function conditionalValidator(predicate, validator) {
return (formControl => {
if (!formControl.parent) {
return null;
}
if (predicate()) {
return validator(formControl);
}
return null;
})
}
//in ngOnInit:
this.myForm = this.fb.group({
myCheckbox: [''],
myEmailField: ['', [
Validators.maxLength(250),
Validators.minLength(5),
Validators.pattern(/.+@.+\..+/),
conditionalValidator(() => this.myForm.get('myCheckbox').value,
pattern(/.+@.+\..+/),)
]]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment