jQuery noPaste plugin

This jQuery plugin prevents the visitors from using paste methods in any form of inputs.

Usage

  1. <input type="text" name="confirm_email" class="noPaste" />
  2.  
  3. <script language="text/javascript">
  4. $(document).ready(function(){
  5.     $("input.noPaste").noPaste();
  6. });
  7. </script>

Compiled code

  1. /**
  2.  * jQuery noPaste plugin
  3.  * This function prevents the user from using copy/paste functions in inputs.
  4.  *
  5.  * @author Daniel Lindén <admin@vebut.se>
  6.  * @version 1.0
  7.  */
  8. jQuery.fn.noPaste=function(){var a=$(this).val();$(this).keyup(function(){var b=$(this).val();b.length>a.length&&b.length!=a.length+1&&$(this).val(a);a=b});$(this).change(function(){$(this).val()!=a&&$(this).val(a)})};

Source code

  1. /**
  2.  * jQuery noPaste plugin
  3.  * This function prevents the user from using copy/paste functions in inputs.
  4.  *
  5.  * @author Daniel Lindén <admin@vebut.se>
  6.  * @version 1.0
  7.  */
  8. jQuery.fn.noPaste = function ()
  9. {
  10.     // Original field value, later on this will hold the value of the field.
  11.     var inputStr = $(this).val();
  12.  
  13.     // Add keyup event handler
  14.     $(this).keyup(function(){
  15.         // New field value after keyup event
  16.         var inputChange = $(this).val();
  17.  
  18.         // Count the length of the new input value and check its length.
  19.         // The length diff must not be greater than 1.
  20.         if (inputChange.length > inputStr.length && inputChange.length != (inputStr.length + 1)) {
  21.             $(this).val(inputStr); // Reset the field value to its earlier value
  22.         }
  23.  
  24.         // Update original value to match the new value if it validates.
  25.         inputStr = inputChange;
  26.     });
  27.  
  28.     // Block mouse paste
  29.     $(this).change(function(){
  30.         // If the value is not equal to the earlier value
  31.         if ($(this).val() != inputStr) {
  32.             $(this).val(inputStr); // Reset the value
  33.         }
  34.     });
  35. };

This post was published June 12th, 2010, by Daniel Lindén. There are no comments. Trackback

Leave a Reply

You must be logged in to post a comment.