input type number not working on ipad

Viewed 22895

I am creating input in ionic which accepts only numbers. This works on all browsers and devices except for safari and ipad. i dont want the user to input anything other than numbers.I tried to do regex validation on input event but that does not stop the user from typing in alphabets. I tried keydown event but I dont get the innerText on keyDown event. please help

4 Answers

I know this is an old question, but I happened to have the same problem, and I noticed that the what worked for me in the end hasn't been provided as an answer, so I'll add the answer for the next guy.

<input type="number" min="0" inputmode="numeric" pattern="[0-9]*" title="Non-negative integral number">

This site explains the reasoning behind the solution in case you are interested.

The gist of it is that pattern="[0-9]*" is what triggers iOS to display a numeric keypad, while min and numeric are there to make sure that other OSes and browsers still work well with type="number".

Edit: iOS 12.2 for the iPad no longer supports the pattern="[0-9]*" fix - perhaps use type=tel instead.

This worked for me:

<!-- HTML ->
<input type="number" onchange="allowOnlyNumbers()"/>
// js
function allowOnlyNumbers(e){
    // check input using regex
    var regex = RegExp(/[0-9]+/g);
    const test_result = regex.test(e.target.value);

    if(test_result){
      e.target.defaultValue = e.target.value;
    }else{
      e.target.value = e.target.defaultValue;
    }
}
Related