Note: This is an updated answer.
(注意:这是更新的答案。)
Comments below refer to an old version which messed around with keycodes.(下面的注释指的是一个旧版本,其中充斥着密钥代码。)
JavaScript(的JavaScript)
Try it yourself on JSFiddle .
(在JSFiddle上尝试一下。)
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 ):
(您可以使用以下setInputFilter
函数来过滤文本<input>
的输入值(支持“复制+粘贴”,“拖动+拖放”,键盘快捷键,上下文菜单操作,不可键入的键,插入符号位置,不同的键盘布局以及所有浏览器自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 = "";
}
});
});
}
You can now use the setInputFilter
function to install an input filter:
(现在,您可以使用setInputFilter
函数安装输入过滤器:)
setInputFilter(document.getElementById("myTextBox"), function(value) {
return /^d*.?d*$/.test(value); // Allow digits and '.' only, using a RegExp
});
See the JSFiddle demo for more input filter examples.
(有关更多输入过滤器示例,请参见JSFiddle演示 。)
Also note that you still must do server side validation!(另请注意,您仍然必须执行服务器端验证!)
jQuery(jQuery的)
There is also a jQuery version of this.
(还有一个jQuery版本。)
See this answer .(看到这个答案 。)
HTML 5(HTML 5)
HTML 5 has a native solution with <input type="number">
(see the specification ), but note that browser support varies:
(HTML 5有一个本机解决方案,其<input type="number">
(请参阅规范 ),但是请注意,浏览器支持有所不同:)
- Most browsers will only validate the input when submitting the form, and not when typing.
(大多数浏览器将仅在提交表单时验证输入,而不在键入时验证输入。)
- Most mobile browsers don't support the
step
, min
and max
attributes.(大多数移动浏览器不支持step
, min
和max
属性。)
- Chrome (version 71.0.3578.98) still allows the user to enter the characters
e
and E
into the field.(Chrome(版本71.0.3578.98)仍然允许用户在字段中输入字符e
和E
)
Also see this question .(也看到这个问题 。)
- Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter any text into the field.
(Firefox(版本64.0)和Edge(EdgeHTML版本17.17134)仍然允许用户在字段中输入任何文本。)
Try it yourself on w3schools.com .
(在w3schools.com上尝试一下。)