0

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

장호정
  • 41
  • 7

1 Answers1

1

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]*$

Callan
  • 1,179
  • 1
  • 7
  • 18
  • I need to display alert when input not number – 장호정 Jul 23 '21 at 06:52
  • 1
    @장호정 That u can do by checking the `formGroup.controls[controlName].invalid`. Make sure to check `formGroup.controls[controlName].touched` is true before displaying the alert, else it will display the alert from the start itself. – Nischaya Sharma Jul 31 '21 at 10:12