This is a place for me to document how I do this techno magician stuphs...

LimitKeypress Jquery Plugin


What Does It Do?

This is a jquery plugin I wrote to invisably validate a text input field on keypress with a regular expression. Under the conditions that:

  • Allow any regular expression
  • Validation independant of cursor location - if a number has been entered and the cursor is moved to the beginning the user may enter a negative symbol (if a negative # is valid)
  • No flash of invalid characters on keypress
  • Allow backspace, enter, and other non character keypress events
  • A selection is not replaced with an invalid keypress - note: paste will replace any selection
  • Must allow paste and auto complete - Invalid characters from pasted content are removed when the focus changes or a key is pressed - there unfortunately will be a display of invalid data because there is currently no cross browser support for a javaScript paste event i have not yet updated this

By default it uses /^[-+]?\d*\.?\d*$/ as the regular expression so that only positive or negative decimal numbers are allowed. The only reason for this being the default is because it is the format that I first wanted when I wrote the plugin.

This only validates if javascript is enabled. Remember to validate your data on the server side as well. Note: this plugin does not validate for null values.


Demo


Implementation

include in the head of your HTML document after jquery:

<script type="text/javascript" src="/jquery-1.3.2.js"></script>
<script type="text/javascript" src="/jquery.limitkeypress.js"></script>

HTML quite standard really... :

<form id="limitkeypress-demo" action="">
  <div class="input-stuphs">
    <p>Any positive or negative floating point #: <input id="input01" class="input-default" size="20" type="text"></p>
    <p>Any positive floating point #: <input id="input02" class="input-pos-float" size="20" type="text"></p>
    <p>Any positive integer #: <input id="input03" class="input-pos-int" size="20" type="text"></p>
    <p>Any First Name: <input id="input04" class="input-name" size="20" type="text"></p>
  </div>
</form>

Add to your JavaScript:

$(document).ready(function() {
  $(".input-default").limitkeypress();
  $(".input-pos-float").limitkeypress({ rexp: /^[+]?\d*\.?\d*$/ }); 
  $(".input-pos-int").limitkeypress({ rexp: /^[+]?\d*$/ }); 
  $(".input-name").limitkeypress({ rexp: /^[A-Za-z]*$/ }); 
});

Download