Search code examples
htmlvalidationxhtmluser-inputescaping

Escaping ampersands input by users through text fields?


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 input by a user? Currently, it's breaking my frontend validation.


Solution

  • 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%>