How to apply Regular Expression to input using jQu

2019-06-04 18:01发布

问题:

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.

回答1:

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
  }       
});


回答2:

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:

$("#Day").keyup(function () {
    var test = /\D/;
    if (test.test($(this).val())) {
        $("#Day").val($(this).val().replace(/\D/g, ""));
    }
});

Demo