Basically, I need to be able to strip script and html from input fields before processing. I am using JQuery, and was hoping to find that there is a standard way of doing that sort of thing. Any ideas?
-
7Don't. You should escape your content on the server.SLaks– SLaks2011-06-12 16:36:47 +00:00Commented Jun 12, 2011 at 16:36
-
I had thought about that, and it is easy enough to do, but was under the impression that it would be wise to prevent potentially harmful scripts from being submitted.ICanoe– ICanoe2011-06-12 16:39:55 +00:00Commented Jun 12, 2011 at 16:39
-
1No, it's wise to ensure the server can handle potentially-malicious scripts instead. And you can't really do a belt-and-braces approach (e.g., doing it on both the client and server), because you end up either trying to detect whether something's encoded properly (vulnerability) or double-encoding it (which is a pain).T.J. Crowder– T.J. Crowder2011-06-12 16:44:31 +00:00Commented Jun 12, 2011 at 16:44
-
Thank you SLaks, probably saved me hours here. How do I accept your answer, it is not showing under the Answers heading?ICanoe– ICanoe2011-06-12 16:50:16 +00:00Commented Jun 12, 2011 at 16:50
-
I added that as an answer; you can now accept it. You're welcome.SLaks– SLaks2011-06-12 18:14:40 +00:00Commented Jun 12, 2011 at 18:14
4 Answers
your html:
<input class="striphtml" name="name" />
your js:
$(document).ready(function() {
// strip all html when text in input changes
$(".striphtml").change(function(){
$(this).val( $(this).text() );
});
});
Result:
<p>This is a test.</p>
will be replaced with:
<p>This is a test.</p>
Attention: As SLaks mentioned you MUST validate your INPUTS on server side!!!
Comments
You have to do it on the server. If you do it on the client, you leave yourself open to people hand-crafting HTTP messages to send to your server, knowing that your server assumes your client code escapes the strings. So, since your server can't assume the content is safe, it has to assume that it isn't safe. (Otherwise you end up double-encoding things, and that becomes a pain.) So it's neither possible, nor appropriate, for your client-side code to do the escaping.
1 Comment
Here is a great tutorial for what you need. As SLaks said, do this server side. Sanitize your input
You could do some regular expression work with specific characters, but that can only help a little bit.