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 text input, and I want to expand the warning if the user enters anything other than letters and numbers.
In the above case, a warning is present no matter what is printed.

+7
source share
5 answers

changes:

 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

+14
source

This line

 regx.test('#user') 

you are testing the string #user and it is a string with a bad character ( # ). Therefore, it will always not be allowed.

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

+2
source

You should check the value of #user, not the string #user

 $("#user").keyup(function(e){ var regx = /^[A-Za-z0-9]+$/; if (!regx.test($('#user').val())) // . {$("#infoUser").html("Alphanumeric only allowed !");} );} 
+2
source
  function isNotAlphanumeric(){ return (! val.match(/^[a-zA-Z]+$/)) //return val.match(/^[a-zA-Z0-9]+$/) ? false : true; } 

therefore, if val is alphanumeric, it returns false. Therefore, based on the return value, appropriate actions are taken. You can call this method on a key up event.

0
source
 $('#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
source

All Articles