$("#user").keyup(function(e){
var regx = /^[A-Za-z0-9]+$/;
if (!regx.test('#user'))
{$("#infoUser").html("Alphanumeric only allowed !");}
);}
#user
是文本输入,如果用户输入除字母和数字之外的任何内容,我想显示警告。在上述情况下,无论键入什么内容,都会出现警告。
最佳答案
改变:
if (!regx.test('#user'))
至
if (!regx.test( $(this).val() ) )
做:
$("#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示例