How to prevent non-alphanumeric input in javascript?

前端 未结 5 1570
暖寄归人
暖寄归人 2021-01-04 22:24
$(\"#user\").keyup(function(e){ 
    var regx = /^[A-Za-z0-9]+$/;
    if (!regx.test(\'#user\')) 
    {$(\"#infoUser\").html(\"Alphanumeric only allowed !\");}
);}
<         


        
5条回答
  •  执笔经年
    2021-01-04 22:55

    change:

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

    to

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

    Do:

    $("#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 example

提交回复
热议问题