首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular Validator,用于检查电子邮件对于数据库集或已登录用户的当前电子邮件是否唯一

Angular Validator,用于检查电子邮件对于数据库集或已登录用户的当前电子邮件是否唯一
EN

Stack Overflow用户
提问于 2020-06-27 00:31:00
回答 1查看 29关注 0票数 0

在我当前的应用程序中,我正在尝试构建一个允许用户更改其电子邮件或用户名的表单。我在表单字段上有一个验证器,因此用户不能拥有与其他用户相同的用户名或密码。我用用户当前的用户名和电子邮件预填充域,但是,如果我单击该域删除一个字符,然后重新应用它,我会触发警告文本。如果当前用户输入了自己的用户名,如何使验证器不会引发错误?

代码语言:javascript
运行
复制
import { Injectable } from '@angular/core';
import { FormControl, AbstractControl } from '@angular/forms';
import { UserinfoService } from 'src/services&Validtors/userinfo.service';
import { map } from 'rxjs/operators';
import { HttpClient, HttpParams } from '@angular/common/http';


@Injectable()
export class EmailValidator {
    constructor(private http:HttpClient) { }


    validateEmailNotTaken(control: AbstractControl) {
        return this.checkEmailNotTaken(control.value).pipe(
          map(res => {
            return res ? null : { emailTaken: true };
          })
        );
      }
    
      
      checkEmailNotTaken(email: string) {
        return this.http.get("http://127.0.0.1:8000/accounts/UserDataEmail/").pipe(
          map((emailList: Array<any>) =>
            emailList.filter(user => user.email === email)
          ),
          map(email => !email.length)
        );
      }




}
EN

回答 1

Stack Overflow用户

发布于 2020-06-27 01:06:01

您需要实现AsyncValidator

代码语言:javascript
运行
复制
import {AbstractControl, AsyncValidator, ValidationErrors} from "@angular/forms";
import {Injectable} from "@angular/core";
import {Observable, of} from "rxjs";
import {catchError, map} from "rxjs/operators";

@Injectable({ providedIn: 'root' })
export class EmailValidator implements AsyncValidator {

  constructor(private emailService: YourEmailService) {}

  validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
    return this.emailService.isEmailTaken(control.value).pipe(
      map(isTaken => (isTaken ? { emailTaken: true } : null)),
      catchError(() => of(null))
    );
  }
}

我强烈建议您在返回Observable<boolean>的服务中创建如上所示的checkEmailTaken

For further details, check "Implementing a custom async validator" in the Angular documentation.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62599067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档