SoftwareSavant
SoftwareSavant

Reputation: 9747

Looping through all form elements

I need to loop through all the form elements and get the text out of them and pull out any unwanted values. Values such as ':,.{}\|*&^%$#@!~`?/ and so forth to ensure that I don't have any injection attacks on my website. I am a javascript noob and I need some help with doing this.

Any advice?

Upvotes: 2

Views: 687

Answers (3)

Justin Helgerson
Justin Helgerson

Reputation: 25531

Since you said jQuery is okay to use:

$(":input").each(function(){
    $(this).val($(this).val().replace(/[^\w\s]/gi, ''));
});

While client side validation can be beneficial to the user experience, server side validation should not be skipped.

Upvotes: 1

Naftali
Naftali

Reputation: 146310

Do validation on the server side.

It will be much safer there :-)


By safer I mean that a user cannot play around with the validation code to make it so his or her inputs go through when they shouldn't.

Or if the user turns off javascript, and you have no server side validation, then your input is not validated at all.

Upvotes: 2

josh.trow
josh.trow

Reputation: 4901

If you must do this, here is a base (vanilla javascript, no libs) to work from:

var els = document.forms[0].elements;
for (var el in els) {
  var val = el.value;
  if  (/[':,.{}\|*&^%$#@!~`?/]/.test(val)) {
    // Potential issue, do your repairs here
    el.value = fixedValue;
  }
}

EDIT: Escaping be damned, I'm sure I should have escaped something in there but I don't much care. :)

Upvotes: 4

Related Questions