$("#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.
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] .
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.
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.
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
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 !");}
);}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With