ICanoe
ICanoe

Reputation: 11

Using JQuery, how can I prevent users from entering script or html into input fields?

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?

Upvotes: 1

Views: 1776

Answers (4)

SLaks
SLaks

Reputation: 887225

You shouldn't be doing this at all.

Instead, you should escape your content on the server.
This way, you can accept malicious input (or < characters) without being harmed by it.

Upvotes: 0

WooDzu
WooDzu

Reputation: 4866

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:

&lt;p&gt;This is a test.&lt;/p&gt;

Attention: As SLaks mentioned you MUST validate your INPUTS on server side!!!

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1073998

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.

Upvotes: 1

lockdown
lockdown

Reputation: 1496

Here is a great tutorial for what you need. As SLaks said, do this server side. Sanitize your input

Tutorial

You could do some regular expression work with specific characters, but that can only help a little bit.

Upvotes: 0

Related Questions