首页 文章

如何进行角度异步验证器超时

提问于
浏览
0

首先,我有这个异步验证器用于密码验证的角度,我试图在html中延迟消息,但它似乎没有工作,我怎么需要调用它工作 . 我通过console.log检查(控制)在函数中它返回预期的结果,但它仍然立即出现在我如何在HTML代码中调用它 .

我将把示例代码放在这里 . 在这里,我使用验证器制作表格 .

constructor(fb: FormBuilder)
  {
    this.form = fb.group({
      password: ['', Validators.required,this.asyncValidator],
      confirmPassword: ['', Validators.required,this.asyncValidator]
    })
  }

这是验证功能 .

asyncValidator(control:FormControl):any{
    return new Promise(
      (resolve) =>{
        setTimeout(() => {
          if((control.password).length < 6 && (control.password).length > 1)
              console.log("true");
          console.log("false");
          resolve(null);
        },2000);
      }
    );
 }

这是我在页面中使用的HTML代码,用于查看延迟的消息(不起作用) .

<div class="alert alert-danger"
  *ngIf="asyncValidator(this.form.controls.password)">Password too short</div>

我如何使用异步验证器,以便我的HTML中的消息出现延迟2秒?

1 回答

  • 0

    您似乎误解了异步验证器的作用以及它们的使用和编写方式 . 因此,您的实施存在很多问题 . 这是你如何解决它们 .

    1. Get rid of the code in your constructor and move it to ngOnInit:

    ngOnInit() {
      this.form = this.fb.group({
        password: ['', [Validators.required], [this.asyncValidator.bind(this)]],
        confirmPassword: ['', [Validators.required], [this.asyncValidator.bind(this)]]
      });
    }
    

    Rationale: constructor s应该是瘦的according to Misko Hevery

    经验丰富的开发人员同意组件应该便宜且安全 .

    并且,async验证器作为第三个参数传递给FormControl

    此外,由于 async 验证器是将由Angular而不是我们调用的函数,我们需要通过在异步验证器函数上调用 bind(this) 来显式设置 this 的上下文 .

    2. Now, the promise returned by the asyncValidator, should resolve to null in case of no error and an error object in case of an error:

    asyncValidator(control: FormControl): any {
      return new Promise(
        (resolve) => {
          setTimeout(() => {
            if ((control.value).length < 6 && (control.value).length > 1)
              resolve(null);
            else
              resolve({
                shortPassword: true
              });
          }, 2000);
        }
      );
    }
    

    3. Create a function that is going to return a boolean based on whether a FormControl is touched and has an error that you're returning from your asyncValidator function:

    getFormControlError(controlName) {
      const control = this.form.get(controlName);
      return control.touched && control.errors && control.errors.shortPassword;
    }
    

    Rationale: 这是我们将在模板中使用的内容 .

    4. Update your template to show the error only if the input field is touched and has that error:

    <form [formGroup]="form">
      Password: <input type="text" formControlName="password">
      <div class="alert alert-danger"
      *ngIf="getFormControlError('password')">Password too short</div>
    
      <br><br>
    
      Confirm Password: <input type="text" formControlName="confirmPassword"> 
      <div class="alert alert-danger"
      *ngIf="getFormControlError('confirmPassword')">Password too short</div>
      <br> 
      <br>
    </form>
    

    这是你的参考Working Sample Stackblitz .

相关问题