0

I implemented angular custom validator which works if I hardcode the main logic this way

import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, FormControl } from '@angular/forms';
import { UserAdministrationService } from "./useradministration.service";

function validateUserNameFactory(userAdministrationService: UserAdministrationService) {
    return (c: FormControl) => {


        return {
            validateUserName: {
                valid: false
            }
        };
    };
}

@Directive({
    selector: '[validateUserName][ngModel],[validateUserName][formControl]',
    providers: [
        { provide: NG_VALIDATORS, useExisting: forwardRef(() => UsernameValidator), multi: true }
    ]
})
export class UsernameValidator {

    validator: Function;

    constructor(private userAdministrationService: UserAdministrationService) {
        this.validator = validateUserNameFactory(userAdministrationService);
    }

    validate(c: FormControl) {
        return this.validator(c);
    }
}

but now I would like to use server call inside and this one is not working

function validateUserNameFactory(userAdministrationService: UserAdministrationService) {
    return (c: FormControl) => {

        const q = new Promise((resolve, reject) => {
            setTimeout(() => {
                userAdministrationService.lookupUser(c.value).subscribe(() => {
                    resolve({
                        validateUserName: {
                            valid: false
                        }});
                }, () => {
                    resolve({
                        validateUserName: {
                            valid: false
                        } });
                });
            }, 1000);
        });
        return q;
    };
}
kosnkov
  • 5,609
  • 13
  • 66
  • 107
  • What exactly not working? is there any error you get or just not called? – Al-Mothafar Sep 26 '17 at 20:07
  • @Al-Mothafar no just validator does not lanuch like if there is a promisse then it is totally not working, like there must be a return imediatly – kosnkov Sep 26 '17 at 20:08

1 Answers1

1

Ok I found the answer, it must be NG_ASYNC_VALIDATORS

kosnkov
  • 5,609
  • 13
  • 66
  • 107
  • was about to refer to it. Might be helpful for future [reference](https://stackoverflow.com/a/36238205/5260710) :) – amal Sep 26 '17 at 22:28