2

After reading tons of articles and StackOverflow responses I still don't get what is the industry standard approach for dealing with user's inputs (textarea and input type="text"). What and how should I escape chars? What and how should be stripped / replaced so JSON will not break, especially when the user can copy-paste some of the weirdest characters ever?

The doubtful solution that I have put in place a long time ago was:

String.prototype.escapeChars = function () {
 return this.replace(/\&/g, '&')
.replace(/\n\r?/g, '
')
.replace(/\n/g, '
')
.replace(/\r/g, '
')
.replace(/\s/g, ' ')
.replace(/\</g, '&#x3c;')
.replace(/\"/g, '&#34;')
.replace(/\'/g, '&#39;')
.replace(/\>/g, '&#x3e;')
.replace(/\\/g, '&#x27;')
.replace(/[^\x00-\x7F]/g, '');
};

I would tremendously appreciate if someone will explain in detail or point to a good tutorial on how it should be done PROPERLY with vanilla js.

Мария
  • 135
  • 12
  • https://stackoverflow.com/questions/295566/sanitize-rewrite-html-on-the-client-side check this one – abby37 Feb 05 '19 at 06:09
  • There are little cases where front-end sanitizing makes sense. You should do it server-side, for the simple reason that you can't be sure the data you're receiving there ever met your script, nor that it ever came from a web-browser... – Kaiido Feb 05 '19 at 06:43
  • @Kaiido what are those cases where front-end sanitizing makes sense? thank you – Мария Feb 05 '19 at 19:13

1 Answers1

2

what is the industry standard approach for dealing with user's inputs

To use an appropriate library for the target data format.

What and how should be stripped / replaced so JSON will not break, especially when the user can copy-paste some of the weirdest characters ever?

Nothing. Just use JSON.stringify and it will handle whatever is thrown at it.

For example, if you were sending data to a web service that expects JSON input:

const name = $('input[name=name]').val();
const address = $('input[name=address]').val();
const ajax = jQuery.ajax({
    method: "POST",
    url: "http://example.com/endpoint",
    contentType: "application/json",
    data: JSON.stringify({ name, address })
});
ajax.then(data => console.log(data));

The doubtful solution that I have put in place a long time ago was…

That looks like it is designed for converting to HTML, not JSON.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335