I've been reading many other questions, like these[1][2][3] for example, but the problem still persists.
I need to find the "cleanest" way to have a HTML input
for mobile devices and which respects all these three rules:
suitable mainly for numbers, integer or float
shows the numeric keypad on mobile devices, on Chrome for Android and Safari for iOS, with no strange extra keys
fully respects the HTML5 rules, tested by W3C validator
I've been across these solutions, which neither of them cumulatively respect those three above rules.
<input type="text" pattern="\d*" />
This solution despite working in iOS and fulfilling HTML rules tested by W3C validator, presents in Chrome Android the full keypad with the QWERTY keyboard.
<input type="number" pattern="\d*" />
This solution works on both systems iOS and Android Chrome, showing the number keypad on both systems, but it throws an HTML validation error with W3C validator:
Attribute pattern is only allowed when the input type is email, password, search, tel, text, or url.
<input type="number" />
This solution passes the W3C HTML test, it shows nice on Chrome, but on iOS keypad it presents several unwanted keys
I see many developers using this solution
<input type="tel" />
But in Android Chrome it doesn't allow dot symbols .
(thus no floats), and the keys have letters, which is superfluous
For your specific task I have the extraordinary solution: we take the best solution with type="text"
and pattern and then add the JavaScript which corrects the type attribute. We do it to pass through W3 validator.
The solution
// iOS detection from: stackoverflow.com/a/9039885 with explanation about MSStream
if(/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream)
{
var inputs = document.querySelectorAll('input[type="number"]');
for(var i = inputs.length; i--;)
inputs[i].setAttribute('pattern', '\\d*');
}
<input type="number" />
My solution respects all your three rules (W3 validator inclusive).
But I have to mention that in this case(with pattern) on iOS we do not have the possibility to put float numbers with numeric keypad because on iOS we do not have any keypad with numbers including points. On Android we have this possibility. If you want to have numeric keypad with float numbers then you have to write for iOS extra solution like follows:
<input type="number" />