有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
你可以附加到key down事件,然后根据你需要过滤键,例如:
<input id="FIELD_ID" name="FIELD_ID" onkeypress="return validateNUM(event,this);" type="text">
实际的JavaScript处理程序是:
function validateNUM(e,field)
{
var key = getKeyEvent(e)
if (specialKey(key)) return true;
if ((key >= 48 && key <= 57) || (key == 46)){
if (key != 46)
return true;
else{
if (field.value.search(/\./) == -1 && field.value.length > 0)
return true;
else
return false;
}
}
function getKeyEvent(e){
var keynum
var keychar
var numcheck
if(window.event) // IE
keynum = e.keyCode
else if(e.which) // Netscape/Firefox/Opera
keynum = e.which
return keynum;
}
其他回答
请记住地区差异(欧洲人使用句点和逗号的方式与美国人相反),加上负号(或将数字用括号括起来表示负数的习惯),加上指数符号(我正要谈到这个)。
JavaScript
你可以用下面的setInputFilter函数过滤text <input>的输入值(支持复制+粘贴,拖放,键盘快捷键,上下文菜单操作,不可输入键,插入号位置,不同的键盘布局,有效性错误消息,以及ie9以来的所有浏览器):
// Restricts input for the given textbox to the given inputFilter function.
function setInputFilter(textbox, inputFilter, errMsg) {
[ "input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) {
textbox.addEventListener(event, function(e) {
if (inputFilter(this.value)) {
// Accepted value.
if ([ "keydown", "mousedown", "focusout" ].indexOf(e.type) >= 0){
this.classList.remove("input-error");
this.setCustomValidity("");
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
}
else if (this.hasOwnProperty("oldValue")) {
// Rejected value: restore the previous one.
this.classList.add("input-error");
this.setCustomValidity(errMsg);
this.reportValidity();
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
else {
// Rejected value: nothing to restore.
this.value = "";
}
});
});
}
你现在可以使用setInputFilter函数来安装一个输入过滤器:
setInputFilter(document.getElementById("myTextBox"), function(value) {
return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp.
}, "Only digits and '.' are allowed");
对输入错误类应用您首选的样式。这里有一个建议:
.input-error{
outline: 1px solid red;
}
请注意,您仍然必须进行服务器端验证!
另一个警告是,这将破坏撤销堆栈,因为它设置了这个。直接价值。 这意味着CtrlZ不能在输入无效字符后撤销输入。
Demo
查看JSFiddle演示以获得更多输入过滤器示例或运行下面的堆栈代码片段:
// Restricts input for the given textbox to the given inputFilter. function setInputFilter(textbox, inputFilter, errMsg) { [ "input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) { textbox.addEventListener(event, function(e) { if (inputFilter(this.value)) { // Accepted value. if ([ "keydown", "mousedown", "focusout" ].indexOf(e.type) >= 0) { this.classList.remove("input-error"); this.setCustomValidity(""); } this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty("oldValue")) { // Rejected value: restore the previous one. this.classList.add("input-error"); this.setCustomValidity(errMsg); this.reportValidity(); this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } else { // Rejected value: nothing to restore. this.value = ""; } }); }); } // Install input filters. setInputFilter(document.getElementById("intTextBox"), function(value) { return /^-?\d*$/.test(value); }, "Must be an integer"); setInputFilter(document.getElementById("uintTextBox"), function(value) { return /^\d*$/.test(value); }, "Must be an unsigned integer"); setInputFilter(document.getElementById("intLimitTextBox"), function(value) { return /^\d*$/.test(value) && (value === "" || parseInt(value) <= 500); }, "Must be between 0 and 500"); setInputFilter(document.getElementById("floatTextBox"), function(value) { return /^-?\d*[.,]?\d*$/.test(value); }, "Must be a floating (real) number"); setInputFilter(document.getElementById("currencyTextBox"), function(value) { return /^-?\d*[.,]?\d{0,2}$/.test(value); }, "Must be a currency value"); setInputFilter(document.getElementById("latinTextBox"), function(value) { return /^[a-z]*$/i.test(value); }, "Must use alphabetic latin characters"); setInputFilter(document.getElementById("hexTextBox"), function(value) { return /^[0-9a-f]*$/i.test(value); }, "Must use hexadecimal characters"); .input-error { outline: 1px solid red; } <h2>JavaScript input filter showcase</h2> <p>Supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and <a href="https://caniuse.com/#feat=input-event" target="_blank">all browsers since IE 9</a>.</p> <p>There is also a <a href="https://jsfiddle.net/emkey08/tvx5e7q3" target="_blank">jQuery version</a> of this.</p> <table> <tr> <td>Integer</td> <td><input id="intTextBox"></td> </tr> <tr> <td>Integer >= 0</td> <td><input id="uintTextBox"></td> </tr> <tr> <td>Integer >= 0 and <= 500</td> <td><input id="intLimitTextBox"></td> </tr> <tr> <td>Float (use . or , as decimal separator)</td> <td><input id="floatTextBox"></td> </tr> <tr> <td>Currency (at most two decimal places)</td> <td><input id="currencyTextBox"></td> </tr> <tr> <td>A-Z only</td> <td><input id="latinTextBox"></td> </tr> <tr> <td>Hexadecimal</td> <td><input id="hexTextBox"></td> </tr> </table>
打印稿
下面是它的TypeScript版本。
function setInputFilter(textbox: Element, inputFilter: (value: string) => boolean, errMsg: string): void {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].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
还有一个jQuery版本。请看这个答案。
HTML5
HTML5有一个原生的解决方案<input type="number">(参见规范和文档)。文档中有这个输入类型的工作演示。
Instead of reading the value property, read the valueAsNumber property of the input to get the typed value as a number rather than a string. Usage inside a <form> is recommended because validation is made easier this way; for example, pressing Enter will automatically show an error message if the value is invalid. You can use the checkValidity method or the requestSubmit method on the entire form in order to explicitly check the validity. Note that you might need to use the required attribute in order to disallow an empty input. You can use the checkValidity method or the validity property on the input element itself in order to explicitly check the validity. You can use reportValidity to show an error message and use setCustomValidity to set your own message.
这种方法从根本上具有不同的用户体验:允许输入无效字符,并且单独执行验证。 这样做的好处是撤销堆栈(CtrlZ)不会中断。 注意,无论您选择哪种方法,都必须执行服务器端验证。
但请注意,浏览器支持不同:
大多数浏览器只在提交表单时验证输入,而在输入时不验证。 大多数移动浏览器不支持step、min和max属性。 Chrome(版本71.0.3578.98)仍然允许用户在字段中输入字符e和e。另请参阅问答为什么HTML输入type="number"允许在字段中输入字母e ? Firefox(版本64.0)和Edge (EdgeHTML版本17.17134)仍然允许用户在字段中输入任何文本。
Demo
document.querySelector("form").addEventListener("submit", (event) => { event.preventDefault(); console.log(`Submit! Number is ${event.target.elements.number.valueAsNumber}, integer is ${event.target.elements.integer.valueAsNumber}, form data is ${JSON.stringify(Object.fromEntries(new FormData(event.target).entries()))}.`); }) label { display: block; } <form> <fieldset> <legend>Get a feel for the UX here:</legend> <label>Enter any number: <input name="number" type="number" step="any" required></label> <label>Enter any integer: <input name="integer" type="number" step="1" required></label> <label>Submit: <input name="submitter" type="submit"></label> </fieldset> </form>
上面的一些答案使用了过时的内容,比如which的使用。
要检查按下的键是否为数字,可以使用keyup eventListener来读取event.key的值。如果不是数字,就不要输入字符。您可以将其他密钥加入白名单。例如,允许用户使用箭头在输入字段中向后或向前导航,或者按退格键并删除输入的数字。
validate (event) {
const isNumber = isFinite(event.key)
const whitelist = ['Backspace','Delete','ArrowDown','ArrowUp','ArrowRight','ArrowLeft']
const whitelistKey = whitelist.includes(event.key)
if (!isNumber && !whitelistKey) {
event.preventDefault()
}
}
有一个更简单的解决方案,之前没有人提到过:
inputmode="numeric"
阅读更多信息:https://css-tricks.com/finger-friendly-numerical-inputs-with-inputmode/
如果你可以使用插件,这里有一个我测试过的。除了膏体外,效果很好。
数字输入
这里是一个演示http://jsfiddle.net/152sumxu/2
下面的代码(库内粘贴)
<div id="plugInDemo" class="vMarginLarge">
<h4>Demo of the plug-in </h4>
<div id="demoFields" class="marginSmall">
<div class="vMarginSmall">
<div>Any Number</div>
<div>
<input type="text" id="anyNumber" />
</div>
</div>
</div>
</div>
<script type="text/javascript">
// Author: Joshua De Leon - File: numericInput.js - Description: Allows only numeric input in an element. - If you happen upon this code, enjoy it, learn from it, and if possible please credit me: www.transtatic.com
(function(b) {
var c = { allowFloat: false, allowNegative: false};
b.fn.numericInput = function(e) {
var f = b.extend({}, c, e);
var d = f.allowFloat;
var g = f.allowNegative;
this.keypress(function(j) {
var i = j.which;
var h = b(this).val();
if (i>0 && (i<48 || i>57)) {
if (d == true && i == 46) {
if (g == true && a(this) == 0 && h.charAt(0) == "-") {
return false
}
if (h.match(/[.]/)) {
return false
}
}
else {
if (g == true && i == 45) {
if (h.charAt(0) == "-") {
return false
}
if (a(this) != 0) {
return false
}
}
else {
if (i == 8) {
return true
}
else {
return false
}
}
}
}
else {
if (i>0 && (i >= 48 && i <= 57)) {
if (g == true && h.charAt(0) == "-" && a(this) == 0) {
return false
}
}
}
});
return this
};
function a(d) {
if (d.selectionStart) {
return d.selectionStart
}
else {
if (document.selection) {
d.focus();
var f = document.selection.createRange();
if (f == null) {
return 0
}
var e = d.createTextRange(), g = e.duplicate();
e.moveToBookmark(f.getBookmark());
g.setEndPoint("EndToStart", e);
return g.text.length
}
}
return 0
}
}(jQuery));
$(function() {
$("#anyNumber").numericInput({ allowFloat: true, allowNegative: true });
});
</script>