验证使用Javascript和打印

时间:2013-05-21 13:31:41

标签: javascript html

我有一个HTML格式的表单,如果字段留空,则Javascript将在字段内打印错误。有人可以给我一段代码来验证表格,然后如果它留空并且不在表格的字段内,则会在表格顶部打印错误吗?

我的表格:

<form id="contact" onsubmit="checkContactForm(); return false;" onreset="resetForm();">
<p>Fill in the form below to send me a message!</p>    

<div id="errormessage"></div>

<p>
<label for="">  </label>
<input type="text" name="" id="" onfocus="" />

<p>
  <label for="name">Name:</label>
  <input type="text" name="name" id="name" onfocus="resetField(this);" />
</p>
<p>
  <label for="email">E-mail address:</label>
  <input type="text" name="email" id="email" onfocus="resetField(this);" />
</p>
<p>
  <label for="message">Your Message:</label>
  <textarea name="message" id="message" rows="5" cols="25" onfocus="resetField(this);"></textarea>
</p>
<p>
  <button type="submit">Send Message</button>
  <button type="reset">Reset Form</button>
</p>

我的Javascript:

var requiredFields = ["name", "email", "message"];

function checkContactForm() {
    var myForm = document.forms[0];
    for (i in requiredFields) {
        fieldName = requiredFields[i];
        if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
            myForm[fieldName].style.color = "#f66";
            myForm[fieldName].value = "";
            var emptyFields = true;
        }
    }

    if (!emptyFields) { myForm.submit(); }
}

function resetField(myField) {
    if (myField.value == "Error") {
        myField.style.color = "#000";
        myField.value = "";
    }
}

function resetForm(myForm) {
    var myForm = document.forms[0];
    for (i in requiredFields) {
        fieldName = requiredFields[i];
        myForm[fieldName].style.color = "#000";
    }
}

2 个答案:

答案 0 :(得分:0)

自HTML5以来,有一个表单验证API(http://www.w3schools.com/js/js_form_validation.asp

在这里你可以找到一个非常好的教程&#34;:http://www.smashingmagazine.com/2009/07/07/web-form-validation-best-practices-and-tutorials/

答案 1 :(得分:0)

如果我理解你想要错误将打印在#errormessage div中,对吗? 如果是这样,你可以简单地做这样的事情:

function addError(str){
    document.getElementById("errormessage").innnerHTML = document.getElementById("errormessage").innerHTML + str + "<br>";
}

function checkContactForm() {
    var myForm = document.forms[0];
    for (i in requiredFields) {
        fieldName = requiredFields[i];
        if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
            myForm[fieldName].style.color = "#f66";
            myForm[fieldName].value = "";
            var emptyFields = true;
            addError(fiedlName+" is empty!");
        }
    }

    if (!emptyFields) { myForm.submit(); }
}