简体   繁体   English

Angular 中唯一的用户名验证,数据从服务返回可观察类型

[英]Unique username validation in Angular with data returns type of observable from service

// register-page.ts //注册-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 // 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 //注册-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.我知道我需要使用一个异步函数来订阅来自accountService.validateUseranem(control.value)的数据,但不知何故我未能使其工作。

Can someone help me on this?有人可以帮我吗?

I did the following and fixed my own problem.我做了以下并解决了我自己的问题。

Created username-validator.directive.ts创建 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. updateOn: 'change' 了解该控件上的输入是否发生变化,并且每当输入发生变化时,它都会检查值以进行验证。

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.因为我需要向 API 发送请求并使用该值返回作为响应,所以我的验证器需要是一个异步验证器。 Also the sync and aysnc validators need to be splitted as far as I understand, like I did.据我所知,同步和 aysnc 验证器也需要分开,就像我所做的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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