Validate Keypress with Regular Expression using a Jquery Plugin

See more about:
(These are the author's views,
not those of CoreDogs.)

Guest post from Brian Jaeger.

This is a jquery plugin 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 - 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

By default it uses /^[-+]?\d*\.?\d*$/ as the regular expression so that only positive or negative decimal numbers are allowed; however, you may change the validation to any regular expression. 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: Here

Implementation:
Put the following in the head of your html:

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



Place this in your jQuery ready function:

  $("selector").limitkeypress();



Use this to change the regular expression(in this example to any word with no numbers):

  $("selector").limitkeypress({ rexp: /^[A-Za-z]*$/ };


I coppied 2 functions to get selection start and end from http://javascript.nwbox.com/cursor_position/

I coppied a function to set a selection from http://www.codingforums.com/archive/index.php/t-90176.html

AttachmentSize
jquery.limitkeypress.js_.txt4.31 KB

Lessons

How to...


Dogs