Input filter showcase

Text input filters with jQuery.

by KarmaProd

HTML

<table>
  <tr><td>Currency (at most two decimal places, less than 100k)</td><td><input id="currencyTextBox"></td></tr>
</table>

JavaScript

// Restricts input for each element in the set of matched elements to the given inputFilter.
(function($) {
  $.fn.inputFilter = function(inputFilter) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function(e) {
      if (e.type == "keydown" && e.which == 110 ){
      	this.value += ",";
      }
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        this.value = "";
      }
    });
  };
}(jQuery));

$("#currencyTextBox").inputFilter(function(value) {
  //return /^-?\d{0,8}[,]?\d{0,2}$/.test(value); });
  return /^-?\d{0,8}[,][\d]{0,2}$|^-?\d{0,8}$/.test(value); });