【问题标题】:Angular 6 - Custom validator for taken emails always returns trueAngular 6 - 接收电子邮件的自定义验证器始终返回 true
【发布时间】:2018-12-06 10:17:15
【问题描述】:

我按照这个 Angular 教程使用了一个自定义验证器来检查是否已经接收了一封电子邮件: https://alligator.io/angular/async-validators/

我的问题是验证器始终返回 true,即使尚未接收电子邮件(数据库中不存在)也是如此。谁能检查我在这里做错了什么?

本教程使用带有电子邮件的 JSON 文件进行检查。我使用连接到 MySQL 数据库的真实后端(spring 框架)。当 http 请求从数据库返回对象时,一切都在那里工作。

这是我的自定义验证器:

export class ValidateEmail {
  static createValidator(registerService: RegisterService) {
    return (control: AbstractControl) => {
      return registerService.findByEmail(control.value).pipe(map(res => {
        return res ? { emailTaken: true } : null;

        // I also tried the below if/else statement, but it changes nothing
        // if(res){
        //   return ({emailTaken: true});
        // } else {
        //   return (null);
        // }

      }));
    }
  }
}

RegisterService 的方法(我认为这里可能有问题?):

  findByEmail(email: string): Observable<User[]> {
    return this.http.get<User[]>('http://localhost:8080/user').pipe(
    map(users => users.filter(user => user.email === email)),
    catchError(this.errorHandler));
  }

向验证器注册组件:

ngOnInit() {
  this.registerForm = this.fb.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    email: ['', [Validators.required, Validators.email], ValidateEmail.createValidator(this.registerService) ],
    username: ['', Validators.required],
    password: ['', [Validators.required, Validators.minLength(5)]]
  });
}

以及带有电子邮件输入字段的表单模板:

<input formControlName="email" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email" name="email"
       [ngClass]="{ 'is-invalid': submitted && f.email.errors }">
<div *ngIf="submitted && f.email.errors" class="invalid-feedback">
  <div *ngIf="f.email.errors.required">Email is required</div>
  <div *ngIf="f.email.errors.email">Email must be a valid email address</div>
  <!-- Below error always shows up, even when email has not been taken -->
  <div *ngIf="f.email.errors.emailTaken">An account with this email already exists</div>
</div>

【问题讨论】:

    标签: angular typescript validation angular-reactive-forms formbuilder


    【解决方案1】:
    return res ? { emailTaken: true } : null;
    

    所以如果res 是真的,验证器会返回一个错误。 res 是什么?这是

    users.filter(user => user.email === email)
    

    所以它是一个数组,可以为空,也可以不为空。一个数组,无论是否为空,总是真实的。所以你的验证器总是返回一个错误。您需要测试数组是否为空。如果是真的,就不会。

    【讨论】:

    • 我将验证器中的检查更改为:if(res.length !== 0),它现在可以工作了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-03-02
    • 2020-12-23
    • 2020-02-23
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    相关资源
    最近更新 更多