我一直在尝试使用以下 JavaScript 代码来验证联系表单上的多个字段。验证适用于要验证的第一个项目(名称字段),但不适用于第二个项目(电子邮件字段)。如果填写了姓名字段,当电子邮件字段为空且表单提交时,验证似乎会跳过电子邮件字段检查。
function validateForm()
{
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
else if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
else
{
return( true );
}
}
以下是联系表单上的 HTML:
<FORM name="contact" METHOD="POST" ACTION="thankyou.php" onsubmit="return validateForm()">
<input type="checkbox" name="newsletter" value="YES" width="30" height="30"> Check the box to subscribe to Herb's Newsletter
<input type="text" class="form-control" size=20 name="name" placeholder="Your name" />
<input type="email" class="form-control" name="email" placeholder="Email Address" />
<input class="btn btn-theme btn-subscribe" type="submit" value="Send" />
</form>
谢谢
最佳答案
您似乎在 if
子句中使用了 empty
函数,该函数似乎没有定义,也不是标准 javascript 函数的一部分。尝试摆脱它:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "") {
alert("Please enter your name.");
document.contact.name.focus();
return false;
} else if (ema == null || ema == "") {
//Check if the email is missing
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
} else {
return true;
}
}
这是一个 live demo .
关于javascript - 常见的 javascript 表单验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41666276/