角度自定义异步验证器无法正常工作

时间:2017-06-27 16:00:22

标签: javascript angular validation angular-forms

这是demo plnkr。我正在尝试为具有文本框和验证按钮的OTP输入实现自定义异步验证器。我想仅在用户单击验证OTP按钮或表单提交按钮时验证输入。目前正在对文本更改事件进行验证,但它无法正常工作。 表单HTML:

<form [formGroup]="registrationForm" (ngSubmit)="registrationForm.valid && submitRegistration(registrationForm.value)" novalidate>
  <fieldset class="form-group">
    <label for="e-mail">Mobile</label>
    <div class="input-group">
      <input type="text" class="form-control" placeholder="Mobile" formControlName="mobile">
      <span class="input-group-btn">
        <button class="btn btn-secondary" type="button">Send OTP</button>
      </span>
    </div>
    <div class="form-text error" *ngIf="registrationForm.controls.mobile.touched">
      <div *ngIf="registrationForm.controls.mobile.hasError('required')">Mobile is required.</div>
    </div>
  </fieldset>
  <fieldset class="form-group">
    <label for="e-mail">Verify OTP</label>
    <div class="input-group">
      <input type="text" class="form-control" placeholder="OTP" formControlName="otp">
      <span class="input-group-btn">
        <button class="btn btn-secondary" (click)="veryOTPAsyn(otp)" type="button">Verify</button>
      </span>
    </div>
    <div class="form-text error" *ngIf="registrationForm.controls.otp.touched">
      <div *ngIf="registrationForm.controls.otp.hasError('required')">OTP is required.</div>
      <div *ngIf="registrationForm.controls.otp.hasError('invalidOtp')">OTP is invalid.</div>
    </div>
  </fieldset>
  <button class='btn btn-primary' type='submit' [disabled]='!registrationForm.valid'>Submit Registration Form</button>
</form>

表单组件:

export class ExampleFormComponent {
  registrationForm: FormGroup;

  constructor(public fb: FormBuilder) {
    // Example use of FormBuilder, FormGroups, and FormControls
    this.registrationForm = fb.group({
      mobile: ['', Validators.required],
      otp: ['', Validators.compose([Validators.required, this.veryOTPAsyn.bind(this)])],
      dob: ['', Validators.required],
      email: ['', Validators.compose([Validators.required,  emailValidator])],
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required],
      firstName: ['', Validators.required],
      lastName: ['', Validators.required]
    }, {validator: matchingPasswords('password', 'confirmPassword')})

  }

  submitRegistration(value: Object): void {
    console.log(value);
  }

  veryOTPAsyn(otpControl: FormControl): Promise<any> {
    console.log(otpControl)
    console.log(otpControl.hasError('invalidOtp'))
    return new Promise<any>(
      (resolve, reject) => {
        setTimeout(() => {
          resolve({invalidOtp:true});
        }, 500);
      });
  }

}

2 个答案:

答案 0 :(得分:1)

试试这个:

 otp: ['', Validators.required, this.veryOTPAsyn.bind(this)]

异步验证器进入第三个参数

答案 1 :(得分:1)

我会考虑删除自定义验证,而是在用户点击按钮时设置/删除错误,因为自定义验证器将在组件初始化时以及输入值更改时运行。所以你的点击事件,并做这样的事情(伪代码):

(click)="veryOTPAsyn(registrationForm.controls.otp)"

和TS:

veryOTPAsyn(ctrl: FormControl) {
  if(ctrl.value == 'hey') {
    ctrl.setErrors({'invalidOtp':true})
  } else {
    ctrl.setErrors({'invalidOtp':null})
  }
}

分叉 PLUNKER

修改

但是如果你想使用异步验证器,只需添加验证器作为第三个参数,但是你不需要验证&#39;按钮。

otp: ['', [Validators.required], [this.veryOTPAsyn]]

或者在v 5.0.0

发布后立即执行此操作
otp: ['', {validators: [Validators.required], asyncValidators: [this.veryOTPAsyn]}]

PLUNKER (在v.5.0.0之前,所以使用了标记异步验证器的第一个选项)