If you work with ASP.NET web apps, and you’re creating input fields that may contain html (like the one I’m typing on right now),you may receive the following error when submitting anything with an angle bracket followed by a letter, such as <a
A potentially dangerous Request.Form value was detected from the client…
Thank you, Microsoft, for saving me from this potential hack! Now, you can simply turn off the security settings, which is explained quite well in this article. However, that leaves you open to all sorts of potential injection attacks, plus it’s against the rules for a lot of sites. You can’t do any string replacements in your code-behind, because this error fires off before any page events have occurred. So my trick is to use jQuery to capture the text before it gets sent to the server, convert any nasty symbols to something safe, then reverse the conversion when the content is displayed.
Just include jquery, add this script anywhere and baddaboom! No more errors.
jQuery(document).ready(function() {
$(”input[type='text'],textarea”).each(function() {
var str = $(this).val();
$(this).val(convertOutput(str));
});
// make inputs safe
$(”input[type='submit'],button”).click(function(event) {
$(”input[type='text'], textarea”).each(function() {
var str = $(this).val();
$(this).val(convertInput(str));
});
});
});
function convertInput(str) {
str = str.replace(/</g, “{{LEFTBRACKET}}”);
str = str.replace(/>/g, “{{RIGHTBRACKET}}”);
return str;
}
function convertOutput(str) {
str = str.replace(/{{LEFTBRACKET}}/g, “<”);
str = str.replace(/{{RIGHTBRACKET}}/g, “>”);
return str;
}
Why not use the built in encode/decode functions?
The thing I hate about using html entities is the fact that the ampersand is used within the symbol it represents! When building custom CMS’s and dealing with outputting text to textareas as well as html blocks, you inevitably trip yourself up if you happen to call encode or decode one too many times, ending up with symbols like this:
&&&lt;
By using a unique string like {{LEFTBRACKET}}, and limiting string replacement to the angle brackets, I find this solution to be a lot more sturdy. If you have a problem with quotes or backslashes, just add them into the conversion functions one at a time.