更新时间:2022-11-26 17:55:15
注意:这是一个更新的答案.下面的评论指的是旧版本,它弄乱了键码.
Note: This is an updated answer. Comments below refer to an old version which messed around with keycodes.
在 JSFiddle 上自己尝试 在 JSFiddle.
您可以使用以下 setInputFilter
函数过滤文本 的输入值(支持复制+粘贴、拖放、键盘快捷键、上下文菜单操作、不可输入的键、插入符号位置、不同的键盘布局以及自 IE 9 以来的所有浏览器):
You can filter the input values of a text <input>
with the following setInputFilter
function (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and all browsers since IE 9):
// Restricts input for the given textbox to the given inputFilter function.
function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
textbox.addEventListener(event, function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
});
}
您现在可以使用 setInputFilter
函数来安装输入过滤器:
You can now use the setInputFilter
function to install an input filter:
setInputFilter(document.getElementById("myTextBox"), function(value) {
return /^d*.?d*$/.test(value); // Allow digits and '.' only, using a RegExp
});
有关更多输入过滤器示例,请参阅 JSFiddle 演示.另请注意,您仍然必须进行服务器端验证!
See the JSFiddle demo for more input filter examples. Also note that you still must do server side validation!
这是一个 TypeScript 版本.
Here is a TypeScript version of this.
function setInputFilter(textbox: Element, inputFilter: (value: string) => boolean): void {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
textbox.addEventListener(event, function(this: (HTMLInputElement | HTMLTextAreaElement) & {oldValue: string; oldSelectionStart: number | null, oldSelectionEnd: number | null}) {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (Object.prototype.hasOwnProperty.call(this, 'oldValue')) {
this.value = this.oldValue;
if (this.oldSelectionStart !== null &&
this.oldSelectionEnd !== null) {
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
} else {
this.value = "";
}
});
});
}
还有一个 jQuery 版本.请参阅此答案.
HTML 5 有一个带有 的原生解决方案(请参阅 规范),但请注意浏览器支持各不相同:
HTML 5 has a native solution with <input type="number">
(see the specification), but note that browser support varies:
step
,min
和 max
属性.e
和 E
.另请参阅这个问题.step
, min
and max
attributes.e
and E
into the field. Also see this question.自己尝试在 w3schools.com.