[英]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. #user
是一个文本输入,如果用户输入除字母和数字之外的任何内容,我想要显示警告。
In the above case, the warning is present whatever is typed. 在上述情况下,无论键入什么都会出现警告。
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
}
});
THis line 这是行
regx.test('#user')
has you testing the string #user
, and that is a string that has a bad character (the #
). 你测试字符串
#user
,这是一个字符不正确的字符串( #
)。 So it will always say not allowed. 所以它总是说不允许。
Use the actual value of your $("#user")
there by using $(this).val()
使用
$(this).val()
使用$(this).val()
$("#user")
的实际值
You must test with #user element value not '#user' string 您必须使用#user元素值而不是'#user'字符串进行测试
$("#user").keyup(function(e){
var regx = /^[A-Za-z0-9]+$/;
if (!regx.test($('#user').val())) // .
{$("#infoUser").html("Alphanumeric only allowed !");}
);}
$('#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;
}
});
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. 所以如果val是字母数字,则返回false。 So based on returned value take appropriate action.
所以基于返回值采取适当的行动。 You can call this method on key up event.
您可以在key up事件上调用此方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.