Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent user pasting text in a textbox?

I have this JS function that prevents user from typing characters

<script type="text/javascript"> function validate(evt) {   var theEvent = evt || window.event;   var key = theEvent.keyCode || theEvent.which;   key = String.fromCharCode(key);   var regex = /[0-9]|\./;   if(!regex.test(key)) {     theEvent.returnValue = false;     if(theEvent.preventDefault) theEvent.preventDefault();   } } </script>  <span>Radio Receive:</span> <input name="ReceiveNo" type="text" class="txtbox" onkeypress='validate(event)' maxlength="11" value="${cpCon.receiveNo}" required tabindex="34" /> 

But I noticed that when the user tried to paste a word from this textbox, the text can be entered. How can I prevent this without disabling the paste?

like image 418
PeterS Avatar asked Mar 10 '13 07:03

PeterS


People also ask

How do I restrict copy and paste in a TextBox?

Disable Copy and Paste in an ASP.NET Webpage TextBox without JavaScript; we need to set the following properties of the TextBox: oncopy="return false" onpaste="return false" oncut="return false"

How do I prevent user input in a TextBox?

The disabled attribute can be set to keep a user from using the <input> element until some other condition has been met (like selecting a checkbox, etc.). Then, a JavaScript could remove the disabled value, and make the <input> element usable. Tip: Disabled <input> elements in a form will not be submitted!

How do I restrict copy and paste?

You can use jquery for this: $('body'). bind('copy paste',function(e) { e. preventDefault(); return false; });

How do I disable input paste?

The onpaste attribute lets us prevent pasting into the form. Adding the autocomplete attribute as well as preventing drag and drop into the element. If you want to avoid the on{event} code in the HTML, you can do it the cleaner way: myElement.


2 Answers

Very Easy Solution:

<input name="ReceiveNo" type="text" class="txtbox" onkeypress='validate(event)' maxlength="11" value="${cpCon.receiveNo}" required tabindex="34" onCopy="return false" onDrag="return false" onDrop="return false" onPaste="return false" autocomplete=off /> 

This worked for me very well. No one can paste now into your textbox using right button paste option of mouse or pressing ctrl+v from the keyboard.

like image 131
arefindev Avatar answered Sep 22 '22 14:09

arefindev


// To Disable the paste functionality

$(document).ready(function(){   $('#txtInput').bind("paste",function(e) {       e.preventDefault();   }); }); 

// Below One might be helpful for your functionality.

$(document).ready(function(){   $('#txtInput').bind("paste",function(e) {     validate(e);   }); }); 

or

OnTabOut() or onblur() you can validate the entered / pasted text instead of handling the paste functionality.

like image 24
Mallikarjuna Reddy Avatar answered Sep 23 '22 14:09

Mallikarjuna Reddy