Fun Infused Games  |   Smooth Operator

  Home   |    Archive   |    About
Posts prior to 8/2/2010 may be missing data. If you need one of those posts, please contact kriswd40@yahoo.com and I will try and recover/find it.

Formatting Text For User Submitted Content
Date 9/18/2008    Tags ASP.net    (0)

When displaying user generated content on a webpage, such as comments, you often want to allow your users to do things like page breaks, bold text, and italic text. You don't want them to have to use HTML to do so (or at least you shouldn't want to, as this opens your site up for cross-site scripting attacks).

It just so happens that I have created a basic format function that does just that. First this function converts anything HTML into a safe display format (so that if you enter code to create something like a table, you'll just see the text <table> instead of the actual table). Next I insert <br /> tags for new line characters so that new lines are preserved exactly how the user types them in.

Finally I added some replaces for [B],[I], ect. so the user can have bold and italic text in their post.

    public string FormatText(string myText)
    {
        // Remove/format HTML
        myText = HttpContext.Current.Server.HtmlEncode(myText);

        // Replace end of line with <BR> tags.
        myText = myText.Replace(Environment.NewLine, "<br />");
        
        // Special formatting
        myText = myText.Replace("[b]", "<b>");
        myText = myText.Replace("[/b]", "</b>");
        myText = myText.Replace("[B]", "<b>");
        myText = myText.Replace("[/B]", "</b>");
        myText = myText.Replace("[i]", "<i>");
        myText = myText.Replace("[/i]", "</i>");
        myText = myText.Replace("[I]", "<i>");
        myText = myText.Replace("[/I]", "</i>");

        return myText;
    }
If you want to be really nice to your user, you can allow them to enter things like links using regular expressions or include a whole set of smileys using a simple replace. I may expand on this example in the future and do just that.

Also of note, while this code takes care of displaying HTML on your page, you probably shouldn't allow users to save HTML to your database in the first place.

kick it on DotNetKicks.com



This article has been view 961 times.


Comments

No comments for this article.


Add Comments

Name *
Website
  Name the animal in the picture below:

*  
Comment *
Insert Cancel
Things To Click


Tags
Video Games (7)  Trivia or Die (3)  SQL (1)  iOS (3)  Game Dev (11)  Advise (14)  PC (1)  World of Chalk (2)  FIN (20)  Abduction Action! (27)  XBLIG (32)  Abduction Action (1)  Nastier (4)  ASP.net (18)  Absurd (2)  Volchaos (11)  Web (19)  Fin (1)  XNA (40)  Rant (50)  Cool (2)  Visual Studio (1)  Trivia Or Die (1)  Xbox (1)  C# (14)  Sports (11)  Design (2)  Development (13)  Hypership (28)  WP7 (8)  VolChaos (1)  Nasty (34)  Abdction Action! (1)