Alegro Alegro - 1 year ago 103
Javascript Question

How to prevent non-alphanumeric input in javascript?

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

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 Source


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


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


    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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download