$("#user").keyup(function(e){
    var regx = /^[A-Za-z0-9]+$/;
    if (!regx.test('#user'))
    {$("#infoUser").html("Alphanumeric only allowed !");}
);}
#user是文本输入,如果用户输入除字母和数字之外的任何内容,我想显示警告。
在上述情况下,无论键入什么内容,都会出现警告。

最佳答案

改变:

if (!regx.test('#user'))


if (!regx.test( $(this).val() ) )

做:
$("#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
    }
});

JS Fiddle示例

10-05 21:05
查看更多