I\'m looking for a way to sanitize input that I paste into the browser, is this possible to do with jQuery?
I\'ve managed to come up with this so far:
Script to remove special characters from all fields with class portlet-form-input-field:
// Remove special chars from input field on paste
jQuery('.portlet-form-input-field').bind('paste', function(e) {
var textInput = jQuery(this);
setTimeout(function() {
textInput.val(replaceSingleEndOfLineCharactersInString(textInput.val()));
}, 200);
});
function replaceSingleEndOfLineCharactersInString(value) {
<%
// deal with end-of-line characters (\n or \r\n) that will affect string length calculation,
// also remove all non-printable control characters that can cause XML validation errors
%>
if (value != "") {
value = value.replace(/(\x00|\x01|\x02|\x03|\x04|\x05|\x06|\x07|\x08|\x0B|\x0C|\x0E|\x0F|\x10|\x11|\x12|\x13|\x14|\x15|\x16|\x17|\x18|\x19|\x1A|\x1B|\x1C|\x1D|\x1E|\x1F|\x7F)/gm,'');
return value = value.replace(/(\r\n|\n|\r)/gm,'##').replace(/(\#\#)/gm,"\r\n");
}
}
This is getting closer to what you might want.
function sanitize(s) {
return s.replace(/\bfoo\b/g, "~");
};
$(function() {
$(":text, textarea").bind("input paste", function(e) {
try {
clipboardData.setData("text",
sanitize(clipboardData.getData("text"))
);
} catch (e) {
$(this).val( sanitize( $(this).val() ) );
}
});
});
Please note that when clipboardData object is not found (on browsers other then IE) you are currently getting the element's full value + the clipboard'ed value.
You can probably do some extra steps to dif the two values, before an input & after the input, if you really are only after what data was truly pasted into the element.
Hmm... I think you can use e.clipboardData
to catch the data being pasted. If it doesn't pan out, have a look here.
$(this).live("paste", function(e) {
alert(e.clipboardData); // [object Clipboard]
});
There is one caveat here. In Firefox, if you reset the input text on every keyup, if the text is longer than the viewable area allowed by the input width, then resetting the value on every keyup breaks the browser functionality that auto scrolls the text to the caret position at the end of the text. Instead the text scrolls back to the beginning leaving the caret out of view.
function scroll(elementToBeScrolled)
{
//this will reset the scroll to the bottom of the viewable area.
elementToBeScrolled.topscroll = elementToBeScrolled.scrollheight;
}
$("#textboxid").on('input propertychange', function () {
//perform operation
});
It will work fine.