1

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?

55SK55
  • 621
  • 2
  • 8
  • 23

1 Answers1

0

You can wrap it with setTimeout(() => {...}, 1000) so it won't set the error immediately, You can do it easily by resolving an error statement or a null, and setting the error only if the current value is the same value that came back from the resolving statement. Notice you will need also to change the validation signature to async validation function.

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91