Search code examples
javascripthtmlajaxescapingunderscore.js-templating

Is there any reason to escape integers in HTML?


If I fetch the following object from the server via Ajax:

$.get('/product/10', function (response) {
  product = response;
    // product:
    // {
    //   name: "Product X",
    //   stock: 20
    // }
});

And then output it to HTML using an Underscore.js template like this:

<input type="number" value="<%- product.name %>">
<input type="number" value="<%= product.stock %>">

Is there any reason to also escape the stock attribute if I know it will always come as an integer from the server?

I can't think of a way to exploit it so I was wondering if an "escape all the things" is a good policy or if an "escape only what you need" is a better one.


Solution

  • If you want to be completely on the safe side, escape everything. Code may change and you may decide to use a string where you previously used a number. If you escape everything, you won't have a problem.

    However, that is just being cautious. If you can guarantee that it will always be a number, even when the AJAX request fails, and in all edge cases, then it's OK not to escape it. Note that everywhere I've worked, the consensus was play it safe.