How to apply Regular Expression to input using jQu

2019-06-04 18:07发布

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.

2条回答
干净又极端
2楼-- · 2019-06-04 18:38

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

查看更多
闹够了就滚
3楼-- · 2019-06-04 18:41

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
  }       
});
查看更多
登录 后发表回答