现有电子邮件的角度异步验证

时间:2019-01-18 09:59:15

标签: angular

早上好,我在验证现有电子邮件时遇到问题, 验证有效,但是当我重写邮件时,它不会脱离错误状态

验证表格

ngOnInit() {
        this.frm = new FormGroup({
            email: new FormControl(null, [Validators.required, Validators.email, this.UsedEmails.bind(this)]),
        });
    }

检查现有电子邮件

UsedEmails(control: FormControl): Promise<any> {
        return new Promise((resolve, reject) => {
            this.usersService.getAdminByEmail(control.value)
                .subscribe(
                    (user: User[]) => {
                        if (user.length) {
                            // does not change state when changing email, allways stays in 
                            // resolve({forbidenEmail: true});
                            console.log("Err!");
                            resolve({
                                forbidenEmail: true
                            });
                        } else {
                            // do not reach
                            console.log("Ok!");
                            resolve(null);
                        }
                    }
                );
        });
    }

usersService

 constructor(
            private http: BaseApi,
        ) { 
    getAdminByEmail(email: string): Observable<User[]> {
            return this.http.get(`auth?email=${email}`);
        }   

html表单

<form [formGroup]="frm" (ngSubmit)="onSubmit()">
        <mat-form-field>
            <input 
                matInput 
                placeholder="Enter your email" 
                formControlName="email"
                required
                (keyup)="OnKeyUpEm($event)"
            >
            <mat-error *ngIf="checkControl('email')">{{getErrMes("email")}}</mat-error>
        </mat-form-field>
        <hr>
        <button type="submit" id="registBut" mat-raised-button [disabled]="frm.invalid">Submit</button>
    </form>

1 个答案:

答案 0 :(得分:0)

我在这里看到一个错误:

email: new FormControl(null, [Validators.required, Validators.email, this.UsedEmails.bind(this)])

您可以在一个数组中提供同步验证器和异步验证器。但是异步验证器必须用作FormControl中的第三个参数:

 email: new FormControl(null, [Validators.required, Validators.email], this.UsedEmails.bind(this))

我还建议您使用observables而不是promise,还建议您使用formBuilder。例如:

 constructor(
    private fb: FormBuilder,
  ) {}

  ngOnInit() {
    this.myForm = this.fb.group({
      name: ['', Validators.required],
      email: [
        '',
        [Validators.required, Validators.email],
        this.validateEmailNotTaken.bind(this)
      ]
    });
  }




  validateEmailNotTaken(control: AbstractControl): Observable {
          // check if email exists
  }