Alegro Alegro - 1 month ago 5
Javascript Question

How to prevent non-alphanumeric input in javascript?

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


#user
is a text input, and I want to diplay a warning if user enters anything except letters and numbers.

In the above case, the warning is present whatever is typed.

Answer

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

Comments