A solution
I don't like to turn off the post validation (validateRequest="false"). On the other hand it is not acceptable that the application crashes just because an innocent user happens to type <x
or something.
Therefore I wrote a client side javascript function (xssCheckValidates) that makes a preliminary check. This function is called when there is an attempt to post the form data, like this:
<form id="form1" runat="server" onsubmit="return xssCheckValidates();">
The function is quite simple and could be improved but it is doing its job.
Please notice that the purpose of this is not to protect the system from hacking, it is meant to protect the users from a bad experience. The request validation done at the server is still turned on, and that is (part of) the protection of the system (to the extent it is capable of doing that).
The reason i say "part of" here is because I have heard that the built in request validation might not be enough, so other complementary means might be necessary to have full protection. But, again, the javascript function I present here has nothing to do with protecting the system. It is only meant to make sure the users will not have a bad experience.
You can try it out here:
function xssCheckValidates() {
var valid = true;
var inp = document.querySelectorAll(
"input:not(:disabled):not([readonly]):not([type=hidden])" +
",textarea:not(:disabled):not([readonly])");
for (var i = 0; i < inp.length; i++) {
if (!inp[i].readOnly) {
if (inp[i].value.indexOf('<') > -1) {
valid = false;
break;
}
if (inp[i].value.indexOf('&#') > -1) {
valid = false;
break;
}
}
}
if (valid) {
return true;
} else {
alert('In one or more of the text fields, you have typed\r\nthe character "<" or the character sequence "&#".\r\n\r\nThis is unfortunately not allowed since\r\nit can be used in hacking attempts.\r\n\r\nPlease edit the field and try again.');
return false;
}
}
<form onsubmit="return xssCheckValidates();" >
Try to type < or &# <br/>
<input type="text" /><br/>
<textarea></textarea>
<input type="submit" value="Send" />
</form>
<httpRuntime requestValidationMode="2.0" />
in web.config