限制HTML输入只允许粘贴 [英] Restrict HTML input to only allow paste

查看:154
本文介绍了限制HTML输入只允许粘贴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在只接受粘贴输入的表单上有HTML输入?

Is it possible to have a HTML input on a form that only accepts pasted input?

作为注册过程的一部分,最终用户需要输入20个字符识别令牌转换为基本的HTML输入表单。理想情况下,用户只需将该令牌复制/粘贴到适当的字段中即可。我们不希望允许用户手动输入,因为他们很可能会输错字母,我们没有任何可靠的方法来验证输入。

As part of our registration process, the enduser needs to enter a 20 character identification token into a basic HTML input form. Ideally, the user would simply copy/paste the token into the appropriate field. We don't want to allow the user to manually type this in, as it is likely that they will mistype letters, and we don't have any reliable means to validate the input.

令牌来自桌面软件,需要粘贴到已经打开的网页(即他们从中下载软件的地方)。因此,一个可点击的链接不是一个可行的选择。

The token comes from desktop software and needs to be pasted into an already opened webpage (i.e. where they download the software from). As such, a clickable link isn't a viable option.

有没有办法做到这一点,例如通过JavaScript?感谢。

Is there any way to do this, e.g. through Javascript? Thanks.

我的解决方案改编自SimplePi的答案:

My solution, adapted from SimplePi's answer:

<html>
<body>
<script type="text/javascript">
 function validate(evt) {
   var theEvent = evt || window.event;
   var key = theEvent.charCode || theEvent.which;

   if(key >= 32 && (theEvent.ctrlKey === undefined || !theEvent.ctrlKey)) {
    if(theEvent.preventDefault) theEvent.preventDefault();
    else theEvent.returnValue = false;
  }
 }
 </script>
  <span>Textbox name</span> <br />
 <input type="text" onkeypress='validate(event)' value=""/>
</body>
</html>

这适用于部分浏览器,但不适用于所有浏览器。 Mac上的Firefox是我发现的唯一罪犯 - 一般情况下firefox会报告 ctrl-v v 完全相同。 ,但在窗口上, theEvent.ctrlKey 成员可以区分这两者。在mac上做同样的事情显然需要keydown / up来检查cmd是否被按下。这是可行的,但不包括在此代码中,以防其他人希望使用此代码。

This works in some, but not all browsers. Firefox on Mac is the only offender I've found - firefox in general reports ctrl-v the exact same as v, but on windows the theEvent.ctrlKey member can differentiate between the two. Doing the same on a mac will apparently require keydown/up to check whether or not cmd is pressed. It's doable, but not included in this code, in case anyone else wishes to use this.

推荐答案

<script type="text/javascript">
 function validate(evt) {
   var theEvent = evt || window.event;
   var key = theEvent.keyCode || theEvent.which;
   key = String.fromCharCode(key);
  var regex = /[]|\./;
   if(!regex.test(key)) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
 }
 </script>
  <span>Textbox name</span>
 <input name="ReceiveNo" type="text" class="txtbox" onkeypress='validate(event)' value=""         required tabindex="" />

这篇关于限制HTML输入只允许粘贴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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