开发者

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 atta开发者_如何转开发cks on my website. I am a javascript noob and I need some help with doing this.

Any advice?


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. :)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜