你只需要将正则表达式更改为:"^[a-zA-Z0-9\-]+$"
。
注意,连字符被使用\
逃脱,否则它用于指定一个范围等a-z
(从a
字符z
)。
这个代码将只检查,如果最后一个输入的字符是在允许列表中,你可能也想在你的领域糊状后检查,该值仍然是正确的:
// The function you currently have
$('#text').keypress(function (e) {
var allowedChars = new RegExp("^[a-zA-Z0-9\-]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (allowedChars.test(str)) {
return true;
}
e.preventDefault();
return false;
}).keyup(function() {
// the addition, which whill check the value after a keyup (triggered by Ctrl+V)
// We take the same regex as for allowedChars, but we add^after the first bracket : it means "all character BUT these"
var forbiddenChars = new RegExp("[^a-zA-Z0-9\-]", 'g');
if (forbiddenChars.test($(this).val())) {
$(this).val($(this).val().replace(forbiddenChars, ''));
}
});
你要逃避它,否则它会尝试检测范围(如'az':' “^ [a-zA-Z0-9 \ - ] + $”'。此外,增加空格将允许空格。 – Sylvain
@Peter我确实在等待这个答案的更新,所以我自己做了一个(有一些补充) 。 – Sylvain