如何在没有 Javascript 的情况下仅强制输入数字? [英] How to force only numbers in a input, without Javascript?

查看:33
本文介绍了如何在没有 Javascript 的情况下仅强制输入数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CodePen:http://codepen.io/leongaban/pen/hbHsk

我在堆栈上找到了这个问题的多个答案这里这里

I've found multiple answers to this question on stack here and here

然而,他们都建议相同的修复,使用 type="number"type="tel"

However they all suggest the same fix, using type="number" or type="tel"

这些都不适用于我的代码笔或项目:(

None of these are working in my codepen or project :(

你看到我遗漏了什么吗?

Do you see what I'm missing?

推荐答案

首先,您使用的是什么浏览器?并非所有浏览器都支持 HTML5 输入类型,因此如果您需要支持可能使用旧浏览器的用户,那么您不能依赖适用于所有用户的 HTML5 输入类型.

Firstly, what browsers are you using? Not all browsers support the HTML5 input types, so if you need to support users who might use old browsers then you can't rely on the HTML5 input types working for all users.

其次,HTML5 输入验证类型不会阻止您输入无效值;他们只是在输入后对输入进行验证.您作为开发人员应该通过使用 CSS 或 JS 来确定字段输入是否无效,并根据需要将其标记给用户.

Secondly the HTML5 input validation types aren't intended to do anything to stop you entering invalid values; they merely do validation on the input once it's entered. You as the developer are supposed to handle this by using CSS or JS to determine whether the field input is invalid, and flag it to the user as appropriate.

如果您真的想防止非数字字符进入该字段,那么答案是肯定的,您需要使用 Javascript(最好的选择是将其捕获在 keyUp 事件中).

If you actually want to prevent non-digit characters from ever getting into the field, then the answer is yes, you need to use Javascript (best option is to trap it in a keyUp event).

您还应该小心确保您在客户端上进行的任何验证也会复制到服务器上,因为任何客户端验证(无论是通过 HTML5 输入字段还是通过您自己的自定义 javascript)都可以通过恶意用户.

You should also be careful to ensure that any validation you do on the client is also replicated on the server, as any client-side validation (whether via the HTML5 input fields or via your own custom javascript) can be bypassed by a malicious user.

这篇关于如何在没有 Javascript 的情况下仅强制输入数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆