表单验证出错

时间:2015-01-05 12:50:50

标签: javascript html forms

我在验证表单时遇到错误。

这是javascript:

function ValidateForm(){
email=document.getElementbyId("email").value;
confirmemail=document.getElementById("confirmemail").value;
password=document.getElementById("password").value;
confirmpassword=document.getElementById("confirmpassword").value;
 errors = " ";

if (email == " ") {
erros += "Please enter your email \n";
}

emailcheck = /^.+@.+\..{2,4}$/;
if (email.match(emailcheck)) { }
else {
errors += "Please check your email \n";
}

if (email.match(confirmemail)) {}
else {
errors += "Email don't match \n";
}

if ( errors != "") {
alert(errors);
}
else { } 
}

这是HTML的形式部分:

<form action="/LoginData/" method="post">
<label>Email</label>
<input id="email" type="email" autocomplete="on" placeholder="Your email id"      name="email" required>
<label>Confirm Email</label>
<input id="confirmemail" type="email" autocomplete="off" placeholder="Confirm your Email id" name="confirmemail" required>
<br/>
<br/>
<label>Password</label>
<input id="password" type="password" name="password" placeholder="Password" required>
<label>Confirm Password</label>
<input id="confirmpassword" type="password" name="confirmpassword" placeholder="Confirm  your Password" required>
<br/>
<br/>
<input type="submit" name="submit" value="Create Account">
</form>

即使我用错误的输入填充字段,它也不会显示警告消息。

(注意:我使用的是外部JavaScript文件)

我正在使用javascript for IE8,因为我想让网页正常运行。 并且它不会显示IE中任何字段的警报。 我尝试构建的示例:1 http://aharrisbooks.net/jad/chap_07/validate.html

2 个答案:

答案 0 :(得分:0)

你必须把

onsubmit="return validateForm()"

所以

<form action="/LoginData/" method="post" onsubmit="return validateForm()">
<label>Email</label>
<input id="email" type="email" autocomplete="on" placeholder="Your email id"      name="email" required>
<label>Confirm Email</label>
<input id="confirmemail" type="email" autocomplete="off" placeholder="Confirm your Email id" name="confirmemail" required>
<br/>
<br/>
<label>Password</label>
<input id="password" type="password" name="password" placeholder="Password" required>
<label>Confirm Password</label>
<input id="confirmpassword" type="password" name="confirmpassword" placeholder="Confirm  your Password" required>
<br/>
<br/>
<input type="submit" name="submit" value="Create Account">
</form>

在表单标记中,以便在提交数据之前使用自定义验证。

您目前使用的是HTML5验证标记,因此即使未调用您的cusom JS函数,您也应该看到使用新浏览器的HTML5验证。您可以通过HTML5查看比其他浏览器更合规的浏览器:http://caniuse.com/#search=html5

答案 1 :(得分:0)

您需要在代码中调用ValidateForm()。

在这种情况下,在提交时调用它将是onsubmit="return validateForm()"之类的最佳选择;

它也有驼峰式问题。应该是getElementById而不是getElementbyId。在浏览器控制台中检查语法错误。