KamaKAzii
8/28/2017 - 11:24 AM

asynccustomvalidator.ts

import { Directive, forwardRef } from "@angular/core";
import { NG_ASYNC_VALIDATORS, Validator, AbstractControl } from "@angular/forms";
import { Observable } from "rxjs";
import { Observer } from "rxjs/Observer";
import { ContactService } from "../../services/contact";

@Directive({
  providers: [
    {
      provide: NG_ASYNC_VALIDATORS,
      useExisting: forwardRef(() => UniqueEmailAsyncValidation),
      multi: true
    }
  ]
})
export class UniqueEmailAsyncValidation implements Validator {

  constructor(
    private contactService: ContactService,
  ) {}

  validate(c : AbstractControl)  {
    return this.checkUnique(c.value).first()
  }

  checkUnique(email: string) {
    return Observable.timer(500).switchMap(() => {
      return this.contactService
        .checkUniqueEmail(email)
        .switchMap((result: boolean) => {
          if (!result) {
            return Observable.of({ emailTaken: true })
          }
          else {
            return Observable.of(null)
          }
        })
    })
  }
}