在表单验证时,如果字段中没有单词,则返回错误,但仍然提交cgi文件

on form validation if there's no words in the fields it returns the error but still submits the cgi file?

本文关键字:错误 返回 cgi 提交 文件 验证 表单 如果 字段 没有单      更新时间:2023-09-26

更具体地说,当我们提交应该有信息的空表单时,应该提交一个警告说"请输入一个值",它会这样做,但在警报上选择ok后,它仍然会在提交时发送电子邮件。我希望它,如果有一个错误,他们必须履行提交的电子邮件可以发送之前的形式的要求。代码是:

检查字段

中是否有值
function notEmpty(elem, helperMsg) {
    if (elem.value.length >= 2) {
        return true;
        alert(helperMsg);
        elem.focus();
        return false;
    }
    return true;
}

表单的开头:

<form method="get" onsubmit="notEmpty();" action="http://www.censoredgaming.co.uk/cgi-bin/mailer.pl">

提交按钮:

<input type="submit" name='Submit' value="Send" onClick='notEmpty();'>

欢迎对我们的问题有任何见解!

失败的原因有几个。

您将遇到的第一个问题是,因为您在调用notEmpty时没有传递任何参数,因此变量elem将是undefined。当您尝试访问它的属性(value)时,将抛出异常并停止函数。

让我们从头开始。

首先,我们将使用一个更现代的方法来应用事件处理程序。

提供一种方法来识别要处理的表单。一般来说,id属性是一个很好的选择(但要使用比I am更有意义的名称):

<form id="myForm"
      method="get"
      action="http://www.censoredgaming.co.uk/cgi-bin/mailer.pl">

接下来,在DOM中获取对表单的引用,并为其添加一个事件侦听器:

document.getElementById('myForm').addEventListener('submit', notEmpty);
注意,您必须在表单已添加到DOM之后执行操作。实现这一点的最简单方法是将<script>放在</form>之后(就在</body>之前是一个受欢迎的位置)。您还可以使用事件处理程序,当DOM准备好或文档已加载时触发。

旧版本的Internet Explorer不支持addEventListerner,如果你想支持它们,请参阅MDN文档,该文档有一个兼容性例程。

接下来,更新notEmpty函数。由于它是一个事件处理程序,因此它将获得一个参数—一个事件对象。它也会在它所绑定的元素(表单)的上下文中被调用。

function notEmpty(event) {
    var aForm = this;
}

您想检查某个元素是否具有一定长度的值,但是在您的问题中没有这样的元素的迹象。让我们来看看这个例子:

<label> Some data <input name="example"></label>

你可以通过表单的元素集合引用元素:

function notEmpty(event) {
    var aForm = this;
    var input = aForm.elements.example;
}

现在你可以添加你的测试:

function notEmpty(event) {
    var aForm = this;
    var input = aForm.elements.example;
    if (input.length >= 2) {
    } else {
    }
}

如果你不希望表单提交,那么阻止事件的默认操作:

function notEmpty(event) {
    var aForm = this;
    var input = aForm.elements.example;
    if (input.length >= 2) {
        // At least two characters, all is well
    } else {
       alert("An error");
       input.focus();
       event.preventDefault();
    }
}

你的第一个return true应该被删除:p