Last active
September 1, 2021 13:40
-
-
Save biased-badger/d894f2c55130fdf747bd2c36161c176a to your computer and use it in GitHub Desktop.
Angular conditional validator
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
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