Ionic 4 ion-input allow number only, restrict alphabet and special character Ionic 4 ion-input allow number only, restrict alphabet and special character typescript typescript

Ionic 4 ion-input allow number only, restrict alphabet and special character


You should use keypress eventHere is the exampleTS File

  numberOnlyValidation(event: any) {    const pattern = /[0-9.,]/;    let inputChar = String.fromCharCode(event.charCode);    if (!pattern.test(inputChar)) {      // invalid character, prevent input      event.preventDefault();    }  }

HTML File

<ion-input type="text" placeholder="Enter number"        [(ngModel)]="userCount"         name="userCount"         (keypress)="numberOnlyValidation($event)" </ion-input>

It will resolve your issue.

Using directive in Ionic 5:

import { Directive, HostListener } from '@angular/core';@Directive({  selector: '[appIntegerInput]'})export class IntegerInputDirective {  constructor() { }  @HostListener('keypress', ['$event'])  onInput(event: any) {    const pattern = /[0-9]/; // without ., for integer only    let inputChar = String.fromCharCode(event.which ? event.which : event.keyCode);    if (!pattern.test(inputChar)) {      // invalid character, prevent input      event.preventDefault();      return false;    }    return true;  }}

HTML File

<ion-input appIntegerInput inputmode="numeric" type="number"></ion-input>


I solved my problem purging the alphabetic characters input following these steps:

  1. I create a util class with method:

export class StringUtil {     /**     * Removes all non numeric characters from string.     * @param str string     */    static removeNonNumerics = (str: string) => str.replace(/\D/g, '');}