文本框只允许输入数字_HTML文本输入仅允许数字输入

本文介绍了如何在HTML中确保文本输入框只接受数字。可以通过JavaScript的onkeypress事件监听并验证ASCII码,或者使用HTML5的number类型输入框来限制输入。同时强调了为了安全,服务器端验证也是必不可少的。
摘要由CSDN通过智能技术生成
文本框只允许输入数字

文本框只允许输入数字

Applications expecting numeric values for the input is generally a pain for developers. Because we have to check given values whether they are number or alphabet. We have some text input element for html. We want to get the number of the person. How can we achieve that easily?

期望输入值为数字的应用程序通常会使开发人员感到痛苦。 因为我们必须检查给定的值是数字还是字母。 我们有一些用于html的文本输入元素。 我们想得到那个人的号码。 我们如何轻松实现这一目标?

纯JavaScript (Pure JavaScript)

By using JavaScript events is the most reliable method. We will write some JavaScript for onkeypress event and check the key code. This is a simple code where we check the entered values ASCII codes and if they are inside the number range we return them.

通过使用JavaScript事件是最可靠的方法。 我们将为onkeypress事件编写一些JavaScript,并检查键代码。 这是一个简单的代码,其中我们检查输入的值ASCII代码,如果它们在数字范围内,则将其返回。

<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
  • onkeypress is the event will be triggered

    onkeypress是事件将被触发

  • return will return code if the code is number which is between 48 and 57

    如果代码是介于48和57之间的数字,则return将返回代码

HTML5(HTML5)

Html5 provides native tag which can only accept numeric input. We can use input tag with the number type which will accept only decimal numbers.

HTML5提供只能接受数字输入的本机标记。 我们可以使用带有number类型的input标签,该类型仅接受十进制数字。

<input type="number">

At least keep in mind that to make things more secure server side filtering is a must. Do not values provided by the client side.

至少要记住,使事情更安全的服务器端过滤是必须的。 不要提供客户端提供的值。

LEARN MORE  How Prompt for Input in Bash
了解更多如何提示输入Bash

翻译自: https://www.poftut.com/html-text-input-allow-numeric-input/

文本框只允许输入数字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值