0

大家好,我正在尝试将验证函数的返回值传递给文档 html 部分中的 innerhtml。由于某种原因无法正常工作....任何帮助表示赞赏。

function validate(form) {
    fail  = validateName(form.name.value)
    fail += validateEmail(form.email.value)
    fail += validateCity(form.city.value)
    if (fail == "") return true
    else { alert(return document.getElementById('#errors').innerHTML=fail;}); return false}
    }

    function validateName(field) {
        if (field == "") return "No name was entered.\n"
        else if (field.length < 3) return "Name must be at least 3 characters.\n"
        else if (!/[a-zA-Z ]*$/.test(field)) return "Name can only have alphabetical characters.\n"
        return ""
        }
    function validateEmail(field) {
        if (field == "") return "No email was entered.\n"
        else if (!((field.indexOf(".") > 0) && (field.indexOf("@") > 0)) || /[^a-zA-Z0-9.@_-]/.test(field)) return "The email address is invalid.\n"
        return ""
        }
    function validateCity(field) {
        if (field == "") return "No city was entered.\n"
        else if (field.length < 3) return "City must be at least 3 characters.\n"
        else if (!/[a-zA-Z ]*$/.test(field)) return "City can only have alphabetical characters.\n"
        return ""
        }



  <form action="<?php echo $editFormAction; ?>" name="subscribe" onSubmit="return validate(this)" id="subscribe" method="POST">
<div id="errors"></div>
<input name="name" autocomplete="off" required pattern="[a-zA-Z ]*$" title="Please enter only alphabetic characters" type="text" id="name" placeholder="Your name"/>


<input name="email" autocomplete="off" required id="email" type="email" title="Please enter your email address" placeholder="Your email address"/>

<input name="city" autocomplete="off" required pattern="[a-zA-Z ]*$" title="Please enter only alphabetic characters" id="city" placeholder="Your city"/>

<section id="buttons">
            <input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset">

            <input type="submit" name="submit" id="submitbtn" class="submitbtn" tabindex="7" value="Submit this!">

            <br style="clear:both;">
        </section>
4

2 回答 2

0

使用错误代替#errorsreturnalertlike中删除

if (fail == "") return true;
else { 
   //use innerText in place of innerHTML if #errors is not a div
   document.getElementById('errors').innerHTML=fail; use errors in place of #errors
   alert(fail);
   return false
}
于 2013-10-15T06:01:53.210 回答
0

对于道德编码,您可能需要避免在函数或方法的参数中返回函数的值:

注意这一行:

else { alert(return document.getElementById('#errors').innerHTML=fail;}); 

是作为 .... 的参数的return一部分传递的,alert()这似乎不太好!

这导致Syntax Errors.

于 2013-10-15T06:20:16.280 回答