Skip to content

Instantly share code, notes, and snippets.

@biased-badger
Last active September 1, 2021 13:40
Show Gist options
  • Save biased-badger/d894f2c55130fdf747bd2c36161c176a to your computer and use it in GitHub Desktop.
Save biased-badger/d894f2c55130fdf747bd2c36161c176a to your computer and use it in GitHub Desktop.
Angular conditional validator
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
/**
* Validates control with `validator` if `predicate` executed on `provider` control value returns `true`
*
* @usageNotes
*
* ### Create a form where `option` is required only when `condition` is `true`
* ```
* const form = new FormGroup({
* condition: new FormControl(false),
* option: new FormControl(
* null,
* conditionalValidator<boolean>('condition', (value) => !!value, Validators.required)
* ),
* });
* ```
*/
export function conditionalValidator<T extends any>(
provider: string,
predicate: (value: T) => boolean,
validator: ValidatorFn | null
): (control: AbstractControl) => ValidationErrors | null {
return (control: AbstractControl) => {
if (!control.parent || !control.parent.get(provider)) {
return null;
}
const m = control.parent.get(provider)!;
if (predicate(m.value) && !!validator) {
return validator(control);
}
return null;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment