views:

255

answers:

1

Like almost all apps today, I have users who enter various information through standard text inputs. My app is running on Rails.

It's a no-brainer to escape ampersands that I include as part of the site copy, etc. But how do I escape an ampersand that is dynamically inputted by a user? Currently, it's totally breaking my frontend validation.

Thanks!

+3  A: 

When you display the values you need to replace certain characters with HTML entities. Those characters are:

& : &
< : &lt;
> : &gt;
" : &quot;

Perhaps there is a HtmlEncode function that you can use for that, otherwise you can use plain string operations. Pseudo code:

output replace(replace(replace(replace(text, "&", "&amp"), "<", "&lt;"), ">", "&gt;", """", "&quot;")

Edit:
I found that you can use the html_escape() function:

<%=html_escape @text%>

Or short:

<%=h @text%>
Guffa
+1 `h` is the Rails way to HTML-escape in a template. **You must always use this!** It's not just a matter of making ampersands look right; if you output text content into HTML without escaping it you've got a cross-site-scripting security hole.
bobince
Follow up tip for other nubes reading this later. In my particular situation, the text was hyperlinked. I'm using the link_to method. If you try doing <%=h link_to url, url %>, then your url will get printed out on the screen. The way to do it is like this: <%=link_to (h(url), url) %>
MikeH