First of all. I prefer to show invalid keystrokes rather than prevent them. The Stack Exchange user stack seems to agree at the moment ( see this question ).
However, not everyone agrees, so let's see what we can do.
Secondly. This does not replace the verification step. There are certain valid key combinations that are not valid numbers, but must be allowed to enter valid numbers. For example, a user can enter a decimal place (a full stop or a comma, depending on the language they use), and then leave a text field and you do not have a real number. The following lines are all number starts, but not yet valid:
The first two are the start of .5 or -.5, while the last two are the same in different languages, which use a comma instead of stopping completely for the decimal place.
This leads us to (already rejected)
<input type="number" step="any">
Of course, you will have to enable a JavaScript script to fix non-modern browsers, but they are available. Theoretically, they should also work correctly when the user works in a language that uses a comma instead of a full stop for the decimal mark. Even better, since users usually use only one browser, and since they will be used to enter the login number in this browser, and since they will spend most of their time on sites other than yours, they can get confused if your site does not behave just like they used to.
But maybe you still want to create your own solution. If everything else fails, I would go with a regex (yes, I know, I now have two problems). I do not believe in resolving spaces, so I limit it to a negative sign, numbers, and one decimal place (depending on what they use). For example:
$('.rational-number').on('keypress', function(e) { if (e.charCode >= 32 && e.charCode < 127 && !/^-?\d*[.,]?\d*$/.test(this.value + '' + String.fromCharCode(e.charCode))) { return false; } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type-"text" class="rational-number">
It ALMOST works. The only problem I am facing right now is assuming that any character you enter goes at the end of the line. This is normal, with the exception of '-' for negative numbers, which is allowed only at the beginning. Thus, you can enter -5.4, but if you type 5.4 and then delete the home key or left arrow before the start, this will not allow you to make it negative.
He will also not engage in insertion. Paste is a complicated topic. I do not agree with the rejection of all operations with the paste. I believe that the best option is to simply let the user insert and let the validator pick up any invalid numbers.