I have this code to force user to enter only numbers in input:
$("#Day").keyup(function()
{
var test =new RegExp( "/\D/G");
if(test.test($("#Day").val()))
$("#Day").val(replace("/\D/G" , ""));
});
but it let me to type non-numbers and no error shown in console.
You can do this without regex:
Add
type="number"
to your input and you should do fine.But, if you want to support IE and HTML 4 users, you can also do this:
Demo
This worked:
JSFIDDLE: http://jsfiddle.net/4RWBU/
I edited your original code in some ways. I change the event type from
keyup
tokeydown
. We can actually prevent the key pressed from display if we usekeydown
but I don't think that is possible to achieve withkeyup
(the key would have already been displayed).