2

I write a function using keydown event to let an input only allow number, '-', and BackSpace key. When I test in ionic serve or iOS, it worked. But when I test in Android device, its not working, input field will allow all the character inputed. When I use console.log (event), it always returns the key=“Unidentified”, keyCode = 229.

Environment: Ionic 3, Node v6.11, NPM 3.10, Android 5.1.1

I don't know how to fix this.

.ts file

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public navCtrl: NavController) {

  }

  isValidNumber(event) {
    //console.log(event);
    return /\d|-|Backspace/.test(event.key);

  }
}

.html file

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>
<ion-content>
  <ion-item>
      <ion-input  type="text" (keydown)="isValidNumber($event)"></ion-input>
  </ion-item> 
</ion-content>
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Elune Crystal
  • 135
  • 2
  • 12

1 Answers1

0

Try the following:

function isValidNumber(e) {
if (
    !(e.keyCode === 8 || !(e.keyCode >= 48 && e.keyCode <= 57) ||  // 0-9
        !(e.keyCode >= 96 && e.keyCode <= 105) // numpad 0-9
        // some more checking like arrows, delete, backspace, etc.
        || e.keyCode == 229)) { // Check for the 'placeholder keyCode'
    return false;
}
{
    // This is not a valid key
    e.preventDefault();
}
return true;

}

Found here

Please read also the following: http://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html

Vega
  • 27,856
  • 27
  • 95
  • 103