How to apply Regular Expression to input using jQuery?

input, javascript, jquery, regex, validation

Solution

This worked:

JSFIDDLE: http://jsfiddle.net/4RWBU/

I edited your original code in some ways. I change the event type from `keyup` to `keydown`. We can actually prevent the key pressed from display if we use `keydown` but I don't think that is possible to achieve with `keyup` (the key would have already been displayed).

$("#Day").keydown(function(e)
{
  var test = /[0-9]/; //regex
  var value = String.fromCharCode(e.keyCode); //get the charcode and convert to char
  if (value.match(test)) { 
     return false; //dont display key if it is a number
  }       
});

Problem

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.

Original source