Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 399
Alegro Avatar asked Jan 15 '13 10:01

Alegro


People also ask

How do you get rid of non-alphanumeric?

A common solution to remove all non-alphanumeric characters from a String is with regular expressions. The idea is to use the regular expression [^A-Za-z0-9] to retain only alphanumeric characters in the string. You can also use [^\w] regular expression, which is equivalent to [^a-zA-Z_0-9] .

How do you restrict the input field alphabets?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

How do I remove non characters from a string?

To remove all non-alphanumeric characters from a string, call the replace() method, passing it a regular expression that matches all non-alphanumeric characters as the first parameter and an empty string as the second. The replace method returns a new string with all matches replaced.


2 Answers

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

like image 166
Sudhir Bastakoti Avatar answered Oct 12 '22 22:10

Sudhir Bastakoti


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 !");}
);}
like image 38
Hossein Avatar answered Oct 12 '22 23:10

Hossein