I have 2 fields in a Form.
<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>
I'm using key-press event to validate the input as below:
omitSpecialCharacters(event) {
return /^[0-9]*$/.test(event.key);
}
In the AppComponent.ts file, I've a Form object and custom validation as below:
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')
});
}
}
My custom validation Code looks like:
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;
};
}
Here, problem is with keypress. When I enter 5 for userIdMinLength field and start entering 10 for userIdMaxLength It will always evaluate the first character from 10 (i.e. 1) and compare with 5 and raises an error.
How to handle this?