如何使 HTML 输入标签只接受数值?

2022-01-17 00:00:00 input numbers html validating

我需要确保某个 <input> 字段仅将数字作为值.输入不是表单的一部分.因此它不会被提交,因此在提交期间进行验证不是一种选择.我希望用户不能输入除数字以外的任何字符.

有没有一种巧妙的方法来实现这一点?

解决方案

HTML 5

您可以使用 HTML5 输入类型编号 仅限制数字条目:

这仅适用于 HTML5 投诉浏览器.确保您的 html 文档的 doctype 是:

<!DOCTYPE html>

另请参阅 https://github.com/jonstipe/number-polyfill 以获得透明支持在旧版浏览器中.

JavaScript

更新:有一个新的非常简单的解决方案:

<块引用>

它允许您在文本 <input> 上使用 任何 类型的输入过滤器,包括各种数字过滤器.这将正确处理复制+粘贴、拖放、键盘快捷键、上下文菜单操作、不可键入的键和所有键盘布局.

请参阅此答案或自己尝试在 JSFiddle 上.

出于一般目的,您可以进行 JS 验证,如下所示:

function isNumberKey(evt){var charCode = (evt.which) ?evt.which : evt.keyCodeif (charCode > 31 && (charCode < 48 || charCode > 57))返回假;返回真;}<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>

如果您想允许小数,请将if 条件"替换为:

if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))

来源:HTML文本输入只允许数字输入p>

JSFiddle 演示:http://jsfiddle.net/viralpatel/nSjy7/

I need to make sure that a certain <input> field only takes numbers as value. The input is not part of a form. Hence it doesn't get submitted, so validating during submission is not an option. I want the user to be unable to type in any characters other than numbers.

Is there a neat way to achieve this?

解决方案

HTML 5

You can use HTML5 input type number to restrict only number entries:

<input type="number" name="someid" />

This will work only in HTML5 complaint browser. Make sure your html document's doctype is:

<!DOCTYPE html>

See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.

JavaScript

Update: There is a new and very simple solution for this:

It allows you to use any kind of input filter on a text <input>, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.

See this answer or try it yourself on JSFiddle.

For general purpose, you can have JS validation as below:

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>

If you want to allow decimals replace the "if condition" with this:

if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))

Source: HTML text input allow only numeric input

JSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/

相关文章