更新时间:2022-11-26 19:04:27
I'd probably do something along the lines of what is described here, while adding in the desired space inclusion: Best way to alphanumeric check in Javascript
例如,查看以下代码片段:
For example, check out this snippet:
function allowAlphaNumericSpace(e) {
var code = ('charCode' in e) ? e.charCode : e.keyCode;
if (!(code == 32) && // space
!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
e.preventDefault();
}
}
<input type="text" onkeypress="allowAlphaNumericSpace(event)" />
根据您的评论,我的快速而又肮脏的解决方案如下,尽管我确定必须存在更好的选择...请注意从"onkeypress"到"onkeyup"的切换,以确保在新值之后更新该值.字符已插入.
Based on your comment, my quick and dirty solution is as follows, though I'm sure a better option must exist... Make note of the switch from "onkeypress" to "onkeyup" to ensure that the value is updated after the new character is inserted.
function allowAlphaNumericSpace(thisInput) {
thisInput.value = thisInput.value.split(/[^a-zA-Z0-9 ]/).join('');
}
<input type="text" onkeyup="allowAlphaNumericSpace(this)" />