Angular 6-模板驱动的表单-检查电子邮件是否已存在

时间:2018-06-30 12:17:38

标签: angular angular-directive angular-forms

我正在尝试检查用户填写表格进行注册的电子邮件是否已经存在。我创建了一个指令来检查它,但是我不知道何时获取已经存在的电子邮件列表以及如何将其传递到验证程序文件。目前,我从“ register.component.ts” 中的数据库中获取用户列表。然后,我尝试使用 appEmailValidator =“ existingEmailsList” 在html中传递它。但是,指令文件中的 console.log(this.emailsList); 会打印字符串existEmailsList而不是列表。

Register.component.html

<div class="jumbotron">
  <div class="container">
    <div class="row">
      <div class="col-sm-6 offset-sm-3">
        <h2>Register</h2>
        <form (submit)="register()" #registerForm="ngForm">

          <div id="emailField">
            <mat-form-field class="full-width">
              <input matInput placeholder="Email" type="text" required appEmailValidator="existingEmailsList" email [(ngModel)]="credentials.email" name="email" #email="ngModel">
            </mat-form-field>
            <div *ngIf="email.invalid && (email.dirty || email.touched)" class="alert alert-danger">
              <div *ngIf="email.errors.required">
                Email is required.
              </div>
              <div *ngIf="email.errors.email">
                Email not valid.
              </div>
              <div *ngIf="name.errors.Email">
                 Email already exists.
             </div>
            </div>
          </div>

          <div id="passwordField">
            <mat-form-field class="full-width">
              <input matInput placeholder="Passwod" type="password" required minlength="7" [(ngModel)]="credentials.password" name="password"
                #password="ngModel">
            </mat-form-field>
            <div *ngIf="password.invalid && (password.dirty || password.touched)" class="alert alert-danger">
              <div *ngIf="password.errors.required">
                Password is required.
              </div>
              <div *ngIf="password.errors.minlength">
                Password must be at least 7 characters long.
              </div>
            </div>
          </div>


          <button type="submit" class="btn btn-success" [disabled]="!registerForm.form.valid">Register!</button>
        </form>
      </div>
    </div>
  </div>
</div>

Register.component.ts

import { Component, OnInit } from "@angular/core";
import { AuthenticationService } from "../../services/authentication.service";
import { Router } from "@angular/router";
import { ApiService } from "../../services/api.service";

@Component({
  selector: "app-register",
  templateUrl: "./register.component.html",
  styleUrls: ["./register.component.scss"]
})
export class RegisterComponent implements OnInit {
  credentials: any = {};
  existingEmailsList: any = [];

  constructor(
    private auth: AuthenticationService,
    private router: Router,
    private api: ApiService
  ) {}

  ngOnInit() {
    this.api.getAllUsers().subscribe(
      data => {
        for (let item in data) {
          this.existingEmailsList.push(data[item].email);
        }
      },
      err => {
        console.log(err);
      }
    );
  }

  register() {
    this.auth.register(this.credentials).subscribe(
      () => {
        this.router.navigateByUrl("/profile");
      },
      err => {
        console.error(err);
      }
    );
  }
}

Email-Validator.directive.ts

import {
  Validator,
  AbstractControl,
  NG_VALIDATORS,
  ValidatorFn
} from "@angular/forms";
import { Directive, Input } from "@angular/core";

export function compareEmails(emailsList: any): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    let alreadyExist = false;
    for (let email of emailsList) {
      if (email === control.value) {
        alreadyExist = true;
      }
    }
    return alreadyExist ? { Email: { value: control.value } } : null;
  };
}

@Directive({
  selector: "[appEmailValidator]",
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: EmailValidatorDirective,
      multi: true
    }
  ]
})
export class EmailValidatorDirective implements Validator {
  @Input("appEmailValidator") emailsList: string;

  validate(control: AbstractControl): { [key: string]: any } | null {
    console.log(this.emailsList);
    return this.emailsList ? compareEmails(this.emailsList)(control) : null;
  }
}

0 个答案:

没有答案