Is there a reason to avoid integers in HTML?
If I receive 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 the Underscore.js template like this:
<input type="number" value="<%- product.name %>">
<input type="number" value="<%= product.stock %>">
Is there any reason to also avoid the attribute stock
if I know it will always be as a whole from the server?
I can't think of how to use it, so I was wondering if "running out of all things" is a good policy or "running away only what you need" is the best.
source to share
If you want to be completely safe, avoid everything. The code may change and you may decide to use the line where you previously used the number. If you avoid everything, you won't have a problem.
However, this is just being careful. If you can guarantee that it will always be a number, even if the AJAX request fails, and in all cases with an edge, then it cannot escape it. Please note that wherever I've worked, consensus has been secure.
source to share
You don't need to hide integers. It might be a good habit to avoid everything altogether and print the original versions of what you intend. However, you can also say that you should trust what comes from the server and not what comes from the client. In the end, it only matters for what you want out of habit. Personally, I wouldn't think of running away from it (because it doesn't have to be avoided), so I would not have avoided it.
source to share
JavaScript is dynamically typed, so there is no way to guarantee that it product.stock
really is a number when the template is received. Any code written in the future using a template (perhaps written by someone else) can pass any value for product
, so it stock
can be of any type.
It is best to always avoid, except in the rare case where you expect the value to actually be HTML, in which case you cannot escape, so future code changes are less likely to break the template.
source to share