表单提交有错误

时间:2014-04-23 18:19:19

标签: javascript php forms validation

我有一个表单,我已经为它编写了验证脚本,但是,它不能100%正常工作。它输出错误很好,但提交按钮将提交表单,即使它已输出警告框。任何人都知道为什么?

显然并非所有代码都粘贴了。我只想使用Required参数,但我需要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;
  }
}

2 个答案:

答案 0 :(得分:2)

只需更改您的html:

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

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

答案 1 :(得分:0)

你没有告诉它不提交表格。 &#34;返回false&#34;只是发回消息。您需要摆脱该OnSubmit标记,并从“提交”按钮调用onClick中的函数。然后,只有当它返回TRUE时,才进行表单提交。