Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate or wrap user inputted HTML to fix unclosed tags

I have text boxes in a form where users can input formatted text or raw HTML. It all works fine, however is a user doesn't close a tag (like a bold tag), then it ruins all HTML formatting after it (it all becomes bold).

Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?

like image 378
Peter R Avatar asked Oct 17 '25 18:10

Peter R


2 Answers

You may try jquery-clean

$.htmlClean($myContent);
like image 155
Mihai Matei Avatar answered Oct 19 '25 09:10

Mihai Matei


Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?

Yes: When the user is done editing the text area, you can parse what they've written using the browser, then get an HTML version of the parsed result from the browser:

var div = $("<div>");
div.html($("#the-textarea").val());
var html = div.html();

Live example — type an unclosed tag in and click the button:

$("input[type=button]").on("click", function() {
    var div = $("<div>");
    div.html($("#the-textarea").val());
    var html = div.html();
    $(document.body).append("<p>You wrote:</p><hr>" + html + "<hr>End of what you wrote.");
});
<p>Type something unclosed here:</p>
<textarea id="the-textarea" rows="5" cols="40"></textarea>
<br><input type="button" value="Click when ready">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Important Note: If you're going to store what they write and then display it to anyone else, there is no client-side solution, including the above, which is safe. Instead, you must use a server-side solution to "sanitize" the HTML you get from them, to remove (for instance) malicious content, etc. All the above does is help you get mostly-well-formed markup, not safe markup.

Even if you're just displaying it to them, it would still be best to sanitize it, since they can work around any client-side pre-processing you do.

like image 22
T.J. Crowder Avatar answered Oct 19 '25 10:10

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!