Pass a dynamic parameter in reactive form custom validator

2.8k views Asked by At

I would like to pass a variable as a parameter in a custom validator like this

    newSimulation: new FormControl('', [uniqNameValidator(this.options)])

Then use it in my custom validator

export function uniqNameValidator(list: any): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const simulationFlatList = list.map(val => val.closingPeriodSimulationName)
    return simulationFlatList.indexOf(control.value) > -1 ? { message: "simulation exists" } : null;
  }
}

The issue with this is that this.options is always empty. I initialize it to [] but when user interacts with the form ( first field ) I update it to an array of string, I think that the custom validator does not recheck the value of this.options ? In this case how to pass a variable in custom validator ?

1

There are 1 answers

0
brooklynDadCore On

this may work, bind the function to component newSimulation: new FormControl('', [uniqNameValidator.bind(this)]) then in the function you can access this.options