如何只强制输入数字,没有Javascript?

编程入门 行业动态 更新时间:2024-10-27 12:37:39
本文介绍了如何只强制输入数字,没有Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

CodePen: codepen.io/leongaban/pen/hbHsk

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

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

或项目:(

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

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

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

CodePen: 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?

本文发布于:2023-11-23 14:54:15,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!