简体   繁体   English

JavaScript表单验证不起作用

[英]Javascript form validation doesn't work

I understand that this is very stupid, but the code between tags just doesn't work. 我知道这很愚蠢,但是标记之间的代码却无法正常工作。

I have a simple HTML registration form. 我有一个简单的HTML注册表格。 And the js-code makes a simple check is any input is empty. 然后,js代码会简单检查所有输入是否为空。

function validate() 
{
    if (document.forms.registration.email.value == "")
    {
        alert("You must provide an email address.");
        return false;
    }
    else if (document.forms.registration.password1.value != document.forms.registration.password2.value)
    {
        alert("You must provide the same password twice");
        return false;
    }
    else if (!document.forms.registration.agreement.checked)
    {
        alert("You must agree to ours terms and conditions");
        return false;
    }
    return true;
}

For some reason the browser kind of ignores this code and submits the form, even if it's empty. 由于某种原因,浏览器会忽略此代码并提交表单,即使它为空。

EDIT: (Added based on OP comment) 编辑:(基于OP注释添加)

<form action="process.php" id="registration" method="get" onsubmit="return.validate();">
        <!-- Other child elements of the form -->
</form>

Replace onsubmit="return.validate();" 替换为onsubmit="return.validate();" by onsubmit="return validate();" 通过onsubmit="return validate();" .
As @showdev did say : 正如@showdev所说的那样:

You don't need the dot. 您不需要点。


You could also use a javascript library such as jQuery to produce your code. 您还可以使用jQuery之类的JavaScript库来生成代码。

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

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