Search code examples
javascripthtmlcsssanitization

How to sanitize JS and HTML in inputs?


I have looked everywhere, but cannot find a simple library or tool for this.

I would like to sanitise comments on my website.

Currently, I can inject HTML, CSS and pretty much whatever I want through comments.

<div id="commentsSection">
    <div class="submitCommentForm">
        <textarea id="commentsInput" required minlength="10" maxlength="150">
        </textarea>
        <div id="submitComment">SUBMIT</div>
    </div>
    <div id="commentsBox"></div>
</div>

What is the best available method ?


Solution

  • Because JavaScript can be disabled, sanitation is not an operation for the frontend; this task should be performed on the backend. Best practice says...

    • Validate input (frontend)
      • Ensure that the data conforms to what you expect before submission
    • Sanitize input (backend)
      • Employ means on the backend to escape or remove unsafe characters before it reaches your application's storage layer
    • Escape output (backend)
      • As an additional safety measure, before outputting, be sure to escape anything coming from a 3rd party source

    You are encouraged to validate data input on the frontend, notifying the user that certain characters are not permitted when trying to submit invalid data. In the event that JavaScript then gets disabled, your backend will still know what to with the malformed data.