Wednesday, October 01, 2008

jQuery: constrain input chars plugin

Problem:
you need to only allow the user to input certain characters into the input box, and you want a jquery plugin to do it!

Solution:


(function($){
$.fn.constrainInput = function(config){
var settings = $.extend({
allowedCharsRegex: ".*"
}, config);
var re = new RegExp(settings.allowedCharsRegex);
$.each(this, function(){
var input = $(this);

var keypressEvent = function(e){
e= e || window.event;
var k = e.charCode || e.keyCode || e.which;
if(e.ctrlKey || e.altKey || k == 8){//Ignore
return true;
} else if ((k >= 41 && k <= 122) ||k == 32 || k > 186){//typeable characters
return (re.test(String.fromCharCode(k)));
}
return false;
}
input.bind("keypress",keypressEvent);
});
return this;
};
})(jQuery);

//usage:




the following lets you specify which chars (regexes or'ed together) are allowed in the input.

i added a small demo for the plugin, check it out here

get the plugin here

4 comments:

Diz said...

Just a small question. Will this "block" even the keyboard shortcuts like Ctrl + C or Ctrl + V ?

Mikhail Koryak said...

@diz: no, it will not, but if you need to do that, i think masked input plugin does that, and you could probably rip out that logic from that plugin. this was meant to be a lightweight version of the same thing, without the "mask".

I suggest adding validation to the inputs on submit, and check for stuff that was pasted in there, or, fix it =)

Chris said...

This is different than using validation how?

Mikhail Koryak said...

@Chris:
i assume you mean using the "validation plugin". Its different because it is very light weight. it doesnt do the 20 billion things that validation does, which can be a good thing sometimes.

Post a Comment