Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
Angular create Async Validator for unique userName

I already code service for Async Validator but I want to code generic Directive for this. Here is my code;

import { Directive } from '@angular/core';
import {AbstractControl, AsyncValidator, NG_ASYNC_VALIDATORS, ValidationErrors} from "@angular/forms";
import {Observable} from "rxjs";
import {IUser} from "app/core/user/user.model";
import {UserService} from "app/core/user/user.service";

@Directive({
  "selector": '[uniqueUsername][ngModel],[uniqueUsername][FormControl]',
  providers: [
    {provide: NG_ASYNC_VALIDATORS, useExisting: UniqueUsernameDirective, multi: true}
  ]
})
export class UniqueUsernameDirective implements AsyncValidator{

  constructor(private userService: UserService) { }

  validate(control: AbstractControl, currentUser?: IUser): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>{
    const promise = new Promise<any>((resolve, reject) => {
      if (currentUser?.login !== control.value) {
        this.userService.userExits(control.value).subscribe(user => {
            if (user?.login !== '') {
              resolve(null);
            }
          },
          response => {
            resolve({'loginAlreadyExits': true});
          });
      }
    });
    return promise;
  }

}

Here is what I am getting error;

/Users/aygunozdemir/IdeaProjects/inuka-ng/src/main/webapp/app/shared/validators/unique-username.directive.ts 10:49 error 'UniqueUsernameDirective' was used before it was defined @typescript-eslint/no-use-before-define

✖ 1 problem (1 error, 0 warnings)

Here is my document ; https://weblog.west-wind.com/posts/2019/Nov/18/Creating-Angular-Synchronous-and-Asynchronous-Validators-for-Template-Validation

Also how can I add input to inside directive, basically

   <input type="text" class="form-control" id="login" name="login" formControlName="login" uniqueUsername[???? shal I put here 'currentUser']>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

To use your uniqueUsername validation directive within your form input control apply it as follows:

<input type="text" class="form-control" id="login" name="login" 
    formControlName="login" uniqueUsername={{currentUser}}> 

Where currentUser is a variable within your component that you wish to validate.

Also remember to declare your validation directive within your application module:

@NgModule({
  declarations: [
    . . . 
    UniqueUsernameDirective
  ],
  ...
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda