【问题标题】:email validation in angular角度的电子邮件验证
【发布时间】:2021-12-06 05:01:16
【问题描述】:

我正在尝试向电子邮件添加验证。

结构:使用响应式表单,获取电子邮件并使用过滤器 javascript 检查是否已存在。

component.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>

错误未显示!我做错了什么?

【问题讨论】:

  • 我有理由确定 返回 一个值没有任何作用;您需要更改应用程序状态。就像this.whatever.exists = true 一样,this 指的是组件
  • 我不明白你的意思,你能更新我的解决方案吗? @ChrisG
  • this.employeeForm.errors.exist = true;替换return {exist: true}
  • 也不起作用@ChrisG
  • 我收到此错误:ERROR TypeError: Cannot set properties of null (setting 'exist')

标签: javascript angular validation form-control


【解决方案1】:

由于验证器使用服务来请求响应,它应该是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;
    }
  }

【讨论】:

  • 我收到此错误:“订阅”类型缺少“可观察”类型中的以下属性/跨度>
  • 对不起@mesterlio,我错过了订阅。我编辑了答案。再次提供的代码是为您指出我认为解决问题的正确方向。请查看提供的官方文档以做出适合您的实施。
  • 不工作@Ruina
猜你喜欢
  • 2015-02-25
  • 2021-02-16
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多