I have a custom validator with parameters set on a FormGroup and it is running once when initialized but is not being triggered on any of the control changes. Removing the parameters runs the validator on each control change but obviously doesn't work without the parameters. Any suggestions to getting this to run on each control change? I've tried to watch the controls and use updateValueAndValidity() and still have no luck.
const customValidator = (options: { min: number, max: number }): ValidatorFn => {
console.log(options);
return (control: AbstractControl): { [key: string]: boolean } | null => {
// logic returning null or { 'not-enough': true }
}
}
this.form = new FormGroup({
controlOne: new FormControl(null),
controlTwo: new FormControl(null)
}, { validators: [customValidator({min: 5, max: 10})]});
Found Solution
Thanks to comments below and other answers I realized that my console logs outside for the return function of the validator only run once. Moving that and any other additional logic inside of the return function, runs as expected. Ultimately my solution was just moving some code down a line...
const customValidator = (options: { min: number, max: number }): ValidatorFn => {
// No code up here will run on each control being validated
return (control: AbstractControl): { [key: string]: boolean } | null => {
// code down here will run on every control change
// logic returning null or { 'not-enough': true }
}
}
this.form = new FormGroup({
controlOne: new FormControl(null),
controlTwo: new FormControl(null)
}, { validators: [customValidator({min: 5, max: 10})]});
optionsparams abovereturnalong with my console logs. I see the factory runs once but the validator is everything in the return function. I moved my logic inside of the return function and all is working now.