javascript - php 和 javascript 表单验证问题

标签 javascript php html forms validation

我使用 bootstrap 创建了一个表单,并使用 javascript 进行表单验证,然后使用 php 脚本获取发布数据并显示它

基本结构如下,为了解决这个特定问题,我已将其尽可能简化。我遇到的问题是检查表单验证的脚本在 <script> 中完美运行。正文末尾的标记,但它并没有阻止页面被提交,因为它应该仍然处理到下一页,其中包含通过 php post 制作的表单内容。当表单确实没有正确填写时采取行动。

这是为什么?表单验证是否仍不能阻止页面移动到发布数据,因为如果表单未正确提交,验证将返回 false。所有表单验证警报都正确弹出,我在检查后没有收到控制台错误,或者我是否需要执行额外的检查以仅在表单有效时处理发布数据?

<html>
   other tags.....
   <body>
      <form name = "OrderForm" action = "process_order.php" onsubmit = "orderbutton" method = "post">
          a bunch of content, divs, checkboxes, etc
      </form>
   </body>
   <script>

            function CheckForm() {
                    var Name = document.getElementById("Name");
                    var fries = document.forms.OrderForm.FryRadio;
                    var fryyes = fries[0].checked
                    var fryno = fries[1].checked

                    var bool = true;

                    if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked)))  {
                         bool = false;
                    }

                    else if (!(fryyes || fryno)) {
                        bool = false;
                    }

                    if (!(bool)) {
                        alert("Please fill out all of the required fields.");
                        return false;
                    }
                    else {
                        alert("Your order is being submitted");
                        console.log("Submitted")
                    }

            };

    </script>
</html>

最佳答案

你应该在 submit 上调用函数,我不知道你在用当前的 onsubmit='...' 做什么

所以在提交表单时使用下面的调用函数。

  <form name = "OrderForm" action = "process_order.php" onsubmit = "return CheckForm()" method = "post">
      a bunch of content, divs, checkboxes, etc
  </form>

演示: Check Fiddle

关于javascript - php 和 javascript 表单验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30115472/

相关文章:

php - 如何在 Laravel 中使用 mysql concat 查询?

html - 在 Symfony 中调整 PDF 大小

javascript - 具有固定列的可滚动表,固定大小相同

jQuery.load 加载 HTML 文件

javascript - 为 json 合并 javascript 数组

php - 在 Laravel 中将数据导出到 Excel

Javascript 类 JQuery 库

php - 为什么我在使用 php sdk 的 Eclipse Indigo 中收到 "Undefined attribute name"警告?

javascript - 将选项动态添加到特定位置的选项组

javascript - 我如何使用 escape 关闭预览窗口,该窗口将要求用户输入他的名字