Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"<" in a text box in ASP.NET --> how to allow it?

I have a textfield which displays a string which contains < and >. The code throws an error because of that. How can I allow the usage of those chars in my textfield?

Thanks :)

like image 751
grady Avatar asked Nov 10 '10 15:11

grady


1 Answers

The easiest solution is to disable request validation in single pages

<%@ Page ... ValidateRequest="false" %>

but don't forget to enable requestValidationMode="2.0"

<system.web>
   ...
   <httpRuntime requestValidationMode="2.0" />
</system.web>

This solution could espose some threats.


Another smart solution is to replace via javascript text written by user to make it safe for validation: <tag> is considere dangerous, but < tag> is considered safe!

A javascript replacement can solve the problem.

function validateTxt() {
    $("textarea, input[type='text']").change(function () {
      html = $(this).val(); //get the value
      //.replace("a" , "b")  works only on first occurrence of "a"
      html = html.replace(/< /g, "<"); //before: if there's space after < remove
      html = html.replace(/</g, "< "); // add space after <
      $(this).val(html); //set new value
   });
}

$(document).ready(function () {
      validateTxt();
});
like image 151
Emanuele Greco Avatar answered Nov 03 '22 23:11

Emanuele Greco