1
votes

I'm trying to create custom validator function in reactive form. Code:

form.component.ts

...
    form = new FormGroup({
        username: new FormControl('', [
            Validators.required,
            Validators.minLength(3)
        ],
            UsernameService.isUnique
        )
    });
...

username.service.ts

...
    static isUnique(control: AbstractControl): Promise<ValidationErrors | null> {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve({ notUnique: true });
            }, 2000);
        });
    }
...

There is an error shown while hovering on UsernameService.isUnique -

"Argument type (control: AbstractControl) => Promise< ValidationErrors | null > is not assignable to parameter type AsyncValidatorFn | AsyncValidatorFn[] | null"

Why this error exists? According to documentation (https://angular.io/api/forms/AsyncValidatorFn) I used proper call signature of AsyncValidatorFn.

2
Did you try to use the isUnique-method without static modifyer? Use public instead. - Lynx 242

2 Answers

0
votes

There was a typescript problem - importing bad type(?) of Promise, I had to add install this module

npm i --save bluebird

and use this as Promise import in component:

import * as Promise from 'bluebird';