How to prevent non-alphanumeric input in javascript?

前端 未结 5 1568
暖寄归人
暖寄归人 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

    0 讨论(0)
  • 2021-01-04 23:02
    $('#alpha').bind('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z\b]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
    });
    
    $('#numeric').bind('keypress', function (event) {
    var regex = new RegExp("^[0-9\b]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
    });
    
    $('#alphanumeric').bind('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9\b]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
    });
    
    
    $('#alphanumericspecial').bind('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9 .]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
    });
    
    0 讨论(0)
  • 2021-01-04 23:05

    THis line

    regx.test('#user')
    

    has you testing the string #user, and that is a string that has a bad character (the #). So it will always say not allowed.

    Use the actual value of your $("#user") there by using $(this).val()

    0 讨论(0)
  • 2021-01-04 23:17
       function isNotAlphanumeric(){
            return (! val.match(/^[a-zA-Z]+$/))
            //return val.match(/^[a-zA-Z0-9]+$/) ? false : true;
       } 
    

    so if val is alpha numeric it return false. So based on returned value take appropriate action. You can call this method on key up event.

    0 讨论(0)
  • 2021-01-04 23:18

    You must test with #user element value not '#user' string

    $("#user").keyup(function(e){ 
        var regx = /^[A-Za-z0-9]+$/;
        if (!regx.test($('#user').val()))  // .
        {$("#infoUser").html("Alphanumeric only allowed !");}
    );}
    
    0 讨论(0)
提交回复
热议问题