且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有 Javascript 的情况下仅强制输入数字?

更新时间:2022-05-02 22:08:33

首先,您使用的是什么浏览器?并非所有浏览器都支持 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.