簡體   English   中英

以角度驗證電子郵件

[英]email validation in angular

我正在嘗試向電子郵件添加驗證。

結構:使用反應式表單,獲取電子郵件並使用過濾器 javascript 檢查是否已經存在。

組件.ts:

  isUniqueEmail(): ValidatorFn {
    return (control: AbstractControl):  any | null => {
      if(control.value.email != null){
      this.httpService
      .getDataFromServer("api/employees?company_branch=" +this.user.branch_id)
      .subscribe((resp) => {
        var data = resp.data.employee;
        
        const found = data.filter(v => v.email == control.value.email);
  
        if(found.length !== 0){
          console.log("found one");
          return {exist: true}
        }
      });
      }
    }
  }

如果電子郵件已經存在 console.log 打印找到並且一切正常。

表單控件的聲明:

  this.employeeForm = new FormGroup({

    email: new FormControl(null,
       [
      Validators.required,
      Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$"),
      ValidatorsSettings.notOnlyWhitespace,
       ]),

  ),{validators: this.isUniqueEmail()}}

在 html 中:

          <div class="row">
            <div class="from-group">
              <label for="Email"> Email </label>
              <mat-divider></mat-divider>

              <input
                type="text"
                id="Email"
                class="form-control"
                formControlName="email"
              />

              <div *ngIf="employeeForm.get('email').invalid && (employeeForm.get('email').touched || employeeForm.get('email').dirty)" class="help-block">
                <div *ngIf="employeeForm.get('email').errors.required || employeeForm.get('email').errors.notOnlyWhitespace" class="help-block">
                    Email is required
                </div>

                <div *ngIf="employeeForm.get('email').errors.pattern" class="help-block">
                    Email must be a valid email address format
                </div>

                <mat-error *ngIf="employeeForm.errors?.exist" class="help-block"
                >Email Already Exist</mat-error>

            </div>

            </div>
          </div>

錯誤不顯示! 我做錯了什么?

由於驗證器正在使用服務來請求響應,因此它應該是asyncValidator 代碼最終可能是:

 isUniqueEmail(): AsyncValidatorFn {
    return (control: AbstractControl): Observable<ValidationErrors>=> {
      if(control.value.email != null){
        return this.httpService
        .getDataFromServer("api/employees?company_branch="+this.user.branch_id).pipe(
        .map((resp) => {
           var data = resp.data.employee;
           const found = data.filter(v => v.email == control.value.email);
           if(found.length !== 0){
             console.log("found one");
             return {exist: true}
           }
        });
      } 
      else return null;
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM