Question

I want a feature of previewing some text with HTML tags and then storing the text in database. I know it is not a good idea to allow HTML in database, for XSS security reasons. What are the ways to achieve this?

I want a feature similar to the one we have in stackoverflow, where we can format our sourcecodes. Thanks.

Was it helpful?

Solution

Recommended way:

Create an javascript event listener for the form on your html-page. Submit the input via ajax to your rails app, where the input gets rendered (for example by the same helper that will later render the output from the database).

Use a markup language like RedCloth/Textile to avoid XSS. It's also easier to type/understand for your users!

Your requested way:

Create an javascript event listener and write the contents of the form/input to another div.

The javascript you'll need depends on which library you use (Prototype or jQuery, for example).

Example:

Suppose you have a form with a textarea, <textarea id="text"></textarea>, and a preview area div with <div id="preview"></div> and you are using Prototype:

document.observe("dom:loaded", function() {
  new Form.Element.Observer('text', 0.25, 
    function () {
      $('preview').update($F('text'));
    }
  );
}

This will check the textarea every 250ms for changes and copy its input into the preview div.

Actually, you just need the code inside the function that is called with document.observe (starting with new Form.Element.Observer.... The document.observe will call this code after the browser has finished building the DOM-tree.

OTHER TIPS

You could also consider using something like textile or markdown, which are ways to achieve HTML markup with plain text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top