How to pass extra param to an async validator (reactive forms) in Angular?

Viewed 1449

I've got the following async validator. If I want to use it to a reactive form, I have to pass it as 3rd param

slug: [null, [Validators.required], [CustomValidators.slug]],

How can I pass an extra param to the validator?

import {FormControl} from "@angular/forms";

interface IValidation {
    [key: string]: boolean;
}

export class CustomValidators {

static slug(control: FormControl) {
    const q = new Promise<IValidation>((resolve, reject) => {
        setTimeout(() => {
            if (control.value === 'TEST') {
                resolve({'duplicated': true});
            } else {
                resolve(null);
            }
        }, 1000);
    });
    return q;
}
}

If I use it as

slug: [null, [Validators.required], [CustomValidators.slug('string param')]],

the problem is that the first param is the control.

1 Answers

Write your validation like this:

static slug(param: string) {
  return (control: FormControl) => {
    const q = new Promise<IValidation>((resolve, reject) => {
      setTimeout(() => {
        if (control.value === 'TEST') {
          resolve({'duplicated': true});
        } else {
          resolve(null);
        }
      }, 1000);
    });
    return q;
  };
}
Related