如何防止javascript中的非字母数字输入?

Ale*_*gro 7 javascript regex jquery

$("#user").keyup(function(e){ 
    var regx = /^[A-Za-z0-9]+$/;
    if (!regx.test('#user')) 
    {$("#infoUser").html("Alphanumeric only allowed !");}
);}
Run Code Online (Sandbox Code Playgroud)

#user是文本输入,如果用户输入除字母和数字之外的任何内容,我想要显示警告.
在上述情况下,无论键入什么都会出现警告.

Sud*_*oti 14

更改:

if (!regx.test('#user')) 
Run Code Online (Sandbox Code Playgroud)

if (!regx.test( $(this).val() ) ) 
Run Code Online (Sandbox Code Playgroud)

做:

$("#user").keyup(function(e){     
    var str = $.trim( $(this).val() );
    if( str != "" ) {
      var regx = /^[A-Za-z0-9]+$/;
      if (!regx.test(str)) {
        $("#infoUser").html("Alphanumeric only allowed !");
      }
    }
    else {
       //empty value -- do something here
    }
});
Run Code Online (Sandbox Code Playgroud)

JS小提琴的例子