简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM