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