Skip to content

Instantly share code, notes, and snippets.

@cuth
Last active January 3, 2016 12:39
Show Gist options
  • Save cuth/8464466 to your computer and use it in GitHub Desktop.
Save cuth/8464466 to your computer and use it in GitHub Desktop.
Limit any text field by adding to data attributes to the field.
(function (exports, $) {
"use strict";
var defaults = {
regexAttr: 'data-regex',
maxAttr: 'data-max'
},
allowedKeys = "Backspace Enter Tab Left Right Down Up",
runRegex = function () {
var value = this.$el.val(),
array = value.match(this.regex),
limited = (array) ? array[0] : "";
if (value === limited) return;
this.$el.val(limited);
},
validateMax = function () {
return (this.$el.val().length >= this.max) ? false : true;
},
bindEvents = function () {
var self = this;
if (this.regex) {
this.$el.on('keyup blur', function () {
runRegex.call(self);
});
}
if (this.max > 0) {
this.$el.on('keypress', function (e) {
if (this.selectionStart != this.selectionEnd) return;
if (allowedKeys.indexOf(e.key) > -1) return;
return validateMax.call(self) ? true : e.preventDefault();
});
}
},
init = function (el, options) {
var regexString;
this.$el = $(el);
if (!this.$el.length) return false;
this.opts = $.extend({}, defaults, options);
regexString = this.$el.attr(this.opts.regexAttr);
if (regexString) {
this.regex = new RegExp(regexString, 'g');
}
this.max = parseInt(this.$el.attr(this.opts.maxAttr), 10);
bindEvents.call(this);
return true;
};
exports.Limit = function (el, options) {
this.result = init.call(this, el, options);
};
}(main, jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment