你只需要將正則表達式更改爲:"^[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