首页 > 解决方案 > Angular 中的自定义验证不适用于 KeyPress 事件

问题描述

我在表单中有 2 个字段。

<input type='text' maxlength='2' formControlName="userIdMinLength" 
class='e-input' (keypress)='omitSpecialCharacters($event);'>

<input type='text' maxlength='2' formControlName="userIdMaxLength" 
class='e-input' (keypress)='omitSpecialCharacters($event);'>

<div class="col-md-12" *ngIf="submitted && f.userIdMaxLength.errors">
     <div class="invalid-feedback">
        <div *ngIf="f.userIdMaxLength.errors.fieldShouldBeGrater">
            The Maximum User ID length should be greater than the Minimum User ID
            length.
        </div>
     </div>
</div>

我正在使用按键事件来验证输入,如下所示:

omitSpecialCharacters(event) {
    return /^[0-9]*$/.test(event.key);
}

AppComponent.ts文件中,我有一个 Form 对象和自定义验证,如下所示:

export class AppComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
  ) {
    this.initializeForm();
  }

  ngOnInit() {
     this.getData();
  }

  initializeForm() {
      this.myFom= this.fb.group({
           userIdMinLength: [null, Validators.required],
           userIdMaxLength: [null, Validators.required],
      },
      {
        validator: [
        FieldShouldBeGreater('userIdMinLength', 'userIdMaxLength')
      });
  }
}

我的自定义验证代码如下所示:

export function FieldShouldBeGreater(sourceControl: string, comparingToControl: string) {
    return (formGroup: FormGroup) => {
        const control = formGroup.controls[sourceControl];
        const comparingTo = formGroup.controls[comparingToControl];

        if (control && comparingTo) {
            if (comparingTo.errors && !comparingTo.errors.fieldShouldBeGrater) {
                return;
            }

            if (control.value > comparingTo.value) {
                comparingTo.setErrors({ fieldShouldBeGrater: true });
            } else {
                comparingTo.setErrors(null);
            }
        }
        return null;
    };
}

在这里,问题在于按键。当我为 userIdMinLength 字段输入 5 并开始为 userIdMaxLength 输入 10 时,它将始终评估 10 中的第一个字符(即 1)并与 5 进行比较并引发错误。

如何处理?

标签: angularangular-reactive-formsrangevalidatorangular-custom-validators

解决方案


您可以将其包装起来,setTimeout(() => {...}, 1000)这样它就不会立即设置错误,您可以通过解析错误语句或 null 来轻松完成此操作,并且仅当当前值与解析语句返回的值相同时才设置错误。请注意,您还需要将验证签名更改为异步验证功能。


推荐阅读