Search code examples
angulartypescriptionic-frameworkeventskeypress

why keypress event is not worked in two input?


I use angular, ionic framework. And I wrote HTML like this

<div><ion-input type="text" id="phoneNumber" [(ngModel)]="phoneNumber" (keypress)="phoneNumericCheck($event)" [disabled]="isSendParamDisabled" maxlength="11" placeholder="{{ 'TEXT.INPUT_FIELD_PHONE_NUMBER' | translate }}"></ion-input></div>
<ion-input [(ngModel)]="authNumber" type="text" id="Auth" maxlength="6" (keypress)="authNumericCheck($event)" placeholder="{{ 'TEXT.INPUT_FIELD_AUTH_NUMBER' | translate }}"></ion-input>

I used different function in two keypress event but It works authNumber but phoneNumber doesn't.

If I use only one keypress event, It works well. I don't know why.

event function has same contents

public phoneNumericCheck(event: any) {
    const pattern = /[0-9.,]/;
    let value = String.fromCharCode(event.charCode);
    let success = pattern.test(value);
    if(!success) {
      event.preventDefault();
      this.alertAboutOnlyNumeric();
    }
  }

and this event does not work sometimes...I dont know why


Solution

  • May I suggest using a different approach for the phone input?

    <ion-input type="tel" autocomplete formControlName="phone"></ion-input>
    
    this.registrationForm = this.fb.group({
      phone: ['', [Validators.required, Validators.pattern(PhoneNumberRegex)]],
    });
    

    for the PhoneNumberRegex you can use a specific phone number format (like here) or simply use ^[0-9]*$