简体   繁体   English

使用JavaScript / HTML进行基本表单验证

[英]Basic Form Validation with JavaScript/HTML

I'm writing a form validation script for my Contact Us form I made. 我正在为我制作的“联系我们”表单编写表单验证脚本。 The script is pretty straight forward, I am wondering why it isn't working correctly. 该脚本非常简单,我想知道为什么它不能正常工作。

No matter what fields I have content in, it always says that field is empty after running the script. 无论我有什么内容,它总是表示运行脚本后该字段为空。

Here is my code: 这是我的代码:

    var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";

function formValidation() {
    if (firstName==="" || firstName=== null)
    {
        errors += "-The First Name field is blank! \n";
    }   
    if (lastName==="" || lastName=== null)
    {
        errors += "-The Last Name field is blank! \n";

    }   
    if (email==="" || email=== null)
    {
        errors += "-The E-mail Address field is blank! \n";

    }
    if (message==="" || message=== null)
    {
        errors += "-The Message field is blank! \n";

    }

    if (errors !== "") {
        alert("Whoops! \n \n" + errors);    
    }
    if (errors === "") {
        alert("Message Sent!");
    }

}

Additionally, here is the jsfiddle I made: http://jsfiddle.net/3DxZj/1/ 此外,这是我制作的jsfiddle: http : //jsfiddle.net/3DxZj/1/

Thank you. 谢谢。

First, you are trying to get the elements by their ids before they exist in the DOM (the script is above the form). 首先,您试图通过元素的ID来获取元素,然后再将它们存在于DOM中(脚本位于表单上方)。

Second, if you corrected that then you would be comparing the HTMLInputElements themselves to an empty string, instead of their .value properties. 其次,如果您对此进行了更正,则可以将HTMLInputElements自身与一个空字符串(而不是它们的.value属性)进行比较。

Third, you never reset errors so if anybody did get an error and them fixed it, they would still get the error alert when they tried again. 第三,您永远不会重置errors因此,如果有人确实得到了错误并修复了错误,那么当他们再次尝试时,他们仍然会收到错误警报。

Add .value to the elements you are trying to get and move the following code so it is inside the function. .value添加到要获取的元素中,然后移动以下代码 ,使其位于函数内部

var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";

You are also only checking for errors when the form is submitted using the submit button. 您还仅在使用“提交”按钮提交表单时检查错误。 You should do this when the form is submitted instead. 您应该在提交表单时执行此操作。

Move the onclick attribute contents to an onsubmit attribute on the form element. onclick属性的内容移动到form元素上的onsubmit属性。 Better yet, bind your event listener with JS . 更好的是, 将事件监听器与JS绑定

You aren't preventing the normal action of the form when there are errors. 出现错误时,您不会阻止表单的正常操作。 Presumably you want it to stop the data from submitting. 大概是您希望它停止提交数据。 Either: 要么:

  1. Use addEventListener (see above), accept an argument for your function and call .preventDefault() on that argument's value when there are errors or 使用addEventListener (请参见上文),为您的函数接受参数,并在出现错误错误时对该参数的值调用.preventDefault()
  2. Add return to the front of your onsubmit attribute value and return false from the function when there are errors. return添加到onsubmit属性值的前面,并在出现错误时从函数return false

Also note that 另请注意

You are querying the dom elements but not their values. 您正在查询dom元素,而不是它们的值。 The correct way would be 正确的方法是

var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";

function formValidation() {
    if (firstName.value==="" || firstName.value=== null)
    {
        errors += "-The First Name field is blank! \n";
    }   
    if (lastName.value==="" || lastName.value=== null)
    {
        errors += "-The Last Name field is blank! \n";

    }   
    if (email.value==="" || email.value=== null)
    {
        errors += "-The E-mail Address field is blank! \n";

    }
    if (message.value==="" || message.value=== null)
    {
        errors += "-The Message field is blank! \n";

    }

    if (errors !== "") {
        alert("Whoops! \n \n" + errors);    
    }
    if (errors === "") {
        alert("Message Sent!");
    }

}

EDIT: Stupid me, didn't check the jsfiddle so I solved only one of your problems while making a mistake in my solution (corrected now), so stick to Quentins answer 编辑:愚蠢的我,没有检查jsfiddle,所以我解决了我的解决方案中的一个错误时,我只解决了您的问题之一(现在已更正),所以请坚持昆汀的回答

The issue is that you are not returning the .value of the form fields. 问题是您没有返回表单字段的.value。

eg: var firstName = document.getElementById("fname").value; 例如:var firstName = document.getElementById(“ fname”)。value;

Also, you should declare your vars inside the function. 另外,您应该在函数中声明您的var。

Try this: 尝试这个:

function formValidation() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
if (firstName==="" || firstName=== null)
{
    errors += "-The First Name field is blank! \n";
}   
if (lastName==="" || lastName=== null)
{
    errors += "-The Last Name field is blank! \n";

}   
if (email==="" || email=== null)
{
    errors += "-The E-mail Address field is blank! \n";

}
if (message==="" || message=== null)
{
    errors += "-The Message field is blank! \n";

}

if (errors !== "") {
    alert("Whoops! \n \n" + errors);    
}
if (errors === "") {
    alert("Message Sent!");
}

} }

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

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