如何只强制输入数字,没有Javascript? [英] How to force only numbers in a input, without Javascript?

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

问题描述

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



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



然而,他们都建议使用 type =number type =tel



或项目:(





你看到我缺少的东西吗? 首先,您使用的浏览器是什么?并非所有浏览器都支持HTML5输入类型,因此如果您需要支持使用旧浏览器的用户那么您不能依赖于HTML5输入类型适用于所有用户。 其次,HTML5输入验证类型无意阻止您输入无效值;他们只是在输入后对输入进行验证。您作为开发人员应该通过使用CSS或JS来确定字段输入是否无效,并在适当时将其标记给用户。



如果您真的想要防止非数字字符进入现场,那么答案是肯定的,你需要使用Javascript(最好的选择是把它放在 keyUp 事件中) 。

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


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

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

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?

解决方案

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.

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.

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).

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天全站免登陆