javascript - 表单提交有错误

标签 javascript php forms validation

我有一个表单,并且我已经为其编写了一个验证脚本,但是它并不能 100% 工作。它可以正常输出错误,但提交按钮将提交表单,即使它已输出警报框。有人知道为什么吗?

显然没有粘贴所有代码。我只想使用必需参数,但我需要 JS 验证,因为它是一个分配。另外,UL 是在这部分代码之前定义的,因为之前有一个列表。

HTML:

<div class = "form">
        <form name = "contactForm" onsubmit="validateForm()" action = "form.php">

        <li><label>First name: </label><input type = "text" name = "fname" autofocus></li>

        <li><label>Last Name: </label><input type = "text" name = "lname"></li>

        <li><label>Email: </label><input type = "text" name = "email"> <button onclick = "validateEmail();return false">Check if email is valid</button> </li>

        <li><label>Message: </label> <br>

            <textarea rows = "10" cols = "50" name = "message"></textarea></li>

        <li> <input type = "submit"> </li>

        </form>

JavaScript:

function validateForm()
{
  var x=document.forms["contactForm"]["fname"].value; //Gets the form and field name from the HTML

  if (x==null || x=="") //If the field "fname" contains null, or nothing, then output an alert telling the user to input something into the field. Same goes for the rest of the code.
  {
    alert("First name must be filled out");
    return false;
  }

  var x=document.forms["contactForm"]["lname"].value;

  if (x==null || x=="") 
  {
    alert("Last name must be filled out");
    return false; 
  }

  var x=document.forms["contactForm"]["email"].value;

  var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; 

  if(reg.test(x) == false)
  {
      alert("Please enter a valid Email");
      return false;
  }

  if (x==null || x=="")
  {
    alert("Email must be filled out");
    return false;
  }

  var x=document.forms["contactForm"]["message"].value;

  if (x==null || x=="")
  {
    alert("Message must be filled out");
    return false;
  }
}

最佳答案

只需更改您的 html:

    <form name = "contactForm" onsubmit="return validateForm()" action = "form.php">

您必须在 ValidateForm() 函数之前添加关键字 return

关于javascript - 表单提交有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23252227/

相关文章:

javascript - 如何在 ReactToPrint 库中自定义打印 pdf 的按钮链接?

php - 将 php 函数返回值转换为 true/false

asp.net-mvc - 如何防止在表单提交时重定向到新页面

Python Mechanize browser.forms()

c# - 提交后禁用按钮

javascript - 防止下载错误文件时出现空白页

javascript - 正则表达式解析 URL 中的术语

javascript - Cassette Add Individual Javascript Script Link Reference 内联

javascript - 使用 JavaScript 调整图像大小并保存到磁盘

php - Laravel 5.3 多文件上传