Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

270
Vistas
Unique username validation in Angular with data returns type of observable from service

// register-page.ts

  this.registerationForm = new FormGroup(
          {
            username: new FormControl(null,
              [
                Validators.required,
                Validators.minLength(3),
                Validators.maxLength(30),
                Validators.pattern('^[a-zA-Z-0123456789]*$'),
    
              ]
            ),

// accountService.ts

validateUsername(username: string): Observable<any> {
    return this.httpManager.post(authServer + "username-validator", new ValidateUsernameRequest(username)).pipe(
        map(
            (response: Response) => {
                return response.data;
            }
        )
    );
}

// register-page.html

<ion-item [ngClass]="username==null ? 'at-beginning':''">
                <ion-label position="floating">Kullanıcı Adı</ion-label>
                <ion-input name="username" formControlName="username" inputmode="text" class="ion-text-lowercase"
                  placeholder="Kullanıcı Adı" (onchange)=(checkUsername($event)) (keypress)=(onKeyUp($event)) (keydown.space)="$event.preventDefault()">
                </ion-input>
              </ion-item>

              <div class="err" *ngIf="formControls.username.errors">
                <div *ngIf="formControls.username.errors.required">Kullanıcı adı zorunlu.</div>
                <div *ngIf="formControls.username.errors.minlength">Kullanıcı adınız çok kısa.</div>
                <div *ngIf="formControls.username.errors.maxlength">Kullanıcı adınız çok uzun.</div>
                <div *ngIf="formControls.username.errors.pattern">Kullanıcı adınız özel karakter içeremez.</div>
                <div *ngIf="formControls.username.errors.checkUsername">Kullanıcı adınız alınmış.</div>
              </div>

I've tried to code a validator for the username that checks its availability whenever the user make changes on the input. I've fight for it two days but I'm just stuck. I understood that I need to use an async function that subscribes the data came from accountService.validateUseranem(control.value) but somehow I failed to make it work.

Can someone help me on this?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I did the following and fixed my own problem.

Created username-validator.directive.ts

import { AbstractControl,  AsyncValidatorFn, ValidationErrors } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { AccountService } from 'src/app/services/yon/auth/account.service';

export function existingUsernameValidator(userService: AccountService): AsyncValidatorFn {
    return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
      return userService.validateUsername(control.value).pipe(map(
        (data) => {
            console.log("The result is : " + data)
          return (!data) ? { "usernameExists": true } : null;
        }
      ));
    };
  } 

Then used it inside of the validators of username

   this.registerationForm = new FormGroup(
          {
            username: new FormControl(null, {
              validators: [
                Validators.required,
                Validators.minLength(3),
                Validators.maxLength(20),
              ],
              asyncValidators: [existingUsernameValidator(this.accountService)],
              updateOn: 'change'
            }),
            email: new FormControl(null, {
              validators: [
                Validators.required,
                Validators.email],
              asyncValidators: [existingEmailValidator(this.accountService)],
              updateOn: 'change'
            }),

like this

Also;

updateOn: 'change' Understands if the input changes on that control and whenever the input changes, it checks the value for validation.

And becasue that I need to send request to API and use that value returns as a response , my validator needed to be an asynchronous validator. Also the sync and aysnc validators need to be splitted as far as I understand, like I did.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda