简体   繁体   中英

How to prevent document.forms[0].submit() from submitting a form?

This is basically my form:

<form method="post" action="" onsubmit="checkallfields(); event.preventDefault();">
  <!-- My Stuff -->
</form>

And it is the first form on my page. I have client-side field validation, which obviously is stored in the function checkallfields() . But the problem is, that the user can be very naughty and open up the console and type document.forms[0].submit() , and then the form will still submit.

How do I prevent this?

You can't prevent it. That is why you need to do serverside validation and that is why you should ALWAYS do serverside validation. The clientside can not be trusted and I do not even need your webpage to submit to your server.

I thought about the problem, and got my own answer. Tested it in Google Chrome.

var i = document.forms.length;
while (i--) {
  document.forms[i].submit = function () {
    return false;
  }
}

Does it work for you guys? You can check here: http://jsfiddle.net/think123/ZRuYw/

Just set that function on the document to false.

document.forms[0].submit = function () {
  return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM