1

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 ?

5
  • have you tried newSimulation: new FormControl('', [uniqNameValidator(this.options)]) it looks to me like you are passing a callback that returns this.options to your validator as the argument Commented May 27, 2021 at 16:49
  • I have updated my answer , actually it was like you mentioned but still not working too Commented May 27, 2021 at 16:51
  • I confirm the custom validator only takes the initial value of options :/ Commented May 27, 2021 at 16:52
  • Its been a minute since I worked with validators, I believe the form control passes control (DynamicFormControlModel or AbstractControl) as the first value, instead of passing in this.options, you can put the validator function in your component and access the options with this Commented May 27, 2021 at 16:56
  • 1
    @infodev have you found a solution to this problem? Cheers Commented Aug 25, 2021 at 5:09

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.