angular - 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 进行比较并引发错误。
如何处理?
解决方案
您可以将其包装起来,setTimeout(() => {...}, 1000)
这样它就不会立即设置错误,您可以通过解析错误语句或 null 来轻松完成此操作,并且仅当当前值与解析语句返回的值相同时才设置错误。请注意,您还需要将验证签名更改为异步验证功能。
推荐阅读
- mysql - 如何构建将利用多个数据源作为其模型的应用程序的数据库?
- javascript - 为什么方法 enumNodeFragments 未定义?
- sql - 如何根据可能更改的日期范围在表格中选择值
- java - 如何在android中构建通知并实现点击监听?
- python - 如何在 Django 的 Inventory 模型中添加多个项目
- php - Laravel 在哪里枢轴
- html - 需要在 SVG 中打勾
- ethereum - Truffle/Ganache:有没有办法设置部署地址?
- sapui5 - 似乎无法将 oData 表连接到智能表
- python - 如何在 pygame 中修复我的精灵动画?