我们有一个文本字段。我们知道如何限制特殊字符。但我们只需要允许字母和数字以及连字符 (-)。不需要特殊字符,但 (-) 除外。给我任何想法。
我的代码:
$('#pduration').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (keyCodeEntered == 45) {
// Allow only 1 minus sign ('-')...
if ((elementRef.value) && (elementRef.value.indexOf('-') >= 0))
return false;
else
return true;
}
}
});
如果我们尝试此代码,它会限制特殊字符,但它允许 -、/、+ 请指导我只允许数字、字母和连字符
最佳答案
替换此部分:
if (keyCodeEntered == 45) {
// Allow only 1 minus sign ('-')...
if ((elementRef.value) && (elementRef.value.indexOf('-') >= 0))
return false;
{
else
return true;
}
用这个:
// keys a-z,0-9 numpad keys 0-9 minus sign backspace
if ( ( key >= 48 && key <= 90 ) || ( key >= 96 && key <= 105 ) || key == 109 || key==8)
{
//return true;
}
else
{
//return false
}
})
关于javascript - 如何限制特殊字符和 (/,*,+) only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28872515/