我在表单中有 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 进行比较并引发错误。
如何处理?