4

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.

2 Answers 2

1

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;
  };
}
Sign up to request clarification or add additional context in comments.

Comments

0

On form declaring you can use your validator like

 @async([(control: AbstractControl) => noMatchControl(control, "oldPassword")])
  newPassword: string;

Here is validator signature

export function noMatchControl(control: AbstractControl<any, any>, targetControl: string): Promise<ValidationErrors | null> {
  return new Promise((resolve) => { ... }}

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.