简体   繁体   English

如何防止 document.forms[0].submit() 提交表单?

[英]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() .我有客户端字段验证,这显然存储在函数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.但问题是,用户可能非常顽皮,打开控制台并输入document.forms[0].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/你可以在这里查看: http : //jsfiddle.net/think123/ZRuYw/

Just set that function on the document to false.只需将文档上的该功能设置为 false。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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