unpollito unpollito - 4 months ago 8x
HTML Question

HTML input that takes only numbers and the + symbol

I am trying to build a custom text input for phone numbers that accepts only numbers and the plus (+) symbol; all other characters need to be discarded and not shown on the field.

I am trying to do this using an event handler (onkeydown/onkeypress) and discarding inputs corresponding to other keys. However, I can't figure out a cross-browser way to do it. Here are the approaches that I have tried and don't work:

  • Using the onkeypress event and looking at event.key to figure out which key was pressed: doesn't work on Chrome (see http://caniuse.com/keyboardevent-key). Is there any cross-browser workaround?

  • Using the onkeycode event and looking at event.keyCode: does not work when we need to press multiple keys to print a character (for instance, an English keyboard layout requires pressing Shift and = to give +). Furthermore, it allows characters such as !@#$%ˆ&*() to appear, as these appear when pressing Shift and a number. (This is the approach followed in JavaScript keycode allow number and plus symbol only, but it does not help me much ;))

  • Using the HTML pattern attribute: this does not really seem to prevent people from writing whatever they feel like.



I put you an example with the event onkeyup.

I use Array.prototype.filter() to remove the bad characters, and Array.prototype.join() to replace the input value.

inputEl = document.getElementById('tel');

inputEl.addEventListener('keyup', function(e) {

  function removeBadEntry(value) {
    var goodEntry = '123456789+ ';
    return (goodEntry.indexOf(value) > -1);
  var filtered = inputEl.value.split('').filter(removeBadEntry);
  inputEl.value = filtered.join("");
<input type='tel' id='tel' />