Restrict HTML input to only allow paste
html, javascript, paste, textfield
Solution
<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="" />
Problem
Is it possible to have a HTML input on a form that only accepts pasted input? 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. Is there any way to do this, e.g. through Javascript? Thanks. 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> ``` 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.