Number only validation not working in ionic app

192 Views Asked by At
      <input type="tel" (keydown)="numberOnlyValidation($event)">

// Function not able to read input number values

// On typing into the input field nothing in showing mainly not able to read the keyboard number values

numberOnlyValidation(event: any) {
        console.log(event.target.value)

//pattern 

        const pattern = /[0-9]/;
        const inputChar = String.fromCharCode(event.charCode);
       

        if (!pattern.test(inputChar)) {
            // invalid character, prevent input
            event.preventDefault();
        }
    }

``
1

There are 1 best solutions below

0
On

The .charCode property only exists on the keypress event Keyboard Event (developer.mozilla.org)

The specification says to use the KeyboardEvent.key property instead (developer.mozilla.org)

Apart from handling delete, your code should work if you change this line to utilize event.key

const inputChar = String.fromCharCode(event.charCode); // remove
const inputChar = event.key; // add