我有 JavaScript 代码,可以在第一次提交请求时验证表单,但是如果用户再次点击提交,即使他们没有纠正表单错误,表单也不会处理验证功能,只会提交。
我希望每次用户单击提交按钮时都执行验证功能。
感谢您的帮助,代码如下。马丁
<form action="site.url" method="post" name="signup" onsubmit="return validateForm()">
<label for="firstname"><span id="inactiveErrorFname">Please enter your first name<br></span>
First name <strong title="Required" class="required">*</strong></label><br>
<input type="text" name="firstName">
<label for="surname"><br><span id="inactiveErrorSname">Please enter your Surname<br></span>
Surname</label><input type="text" name="lastName">
<label for="email">
<span id="inactiveErrorEmail"><br>Please enter your Email address<br></span>
Email address <strong title="Required" class="required">*</strong></label>
<input type="text" name="emailAddress">
<input class="button" type="submit" value="Sign up" />
</form>
<script>
function validateForm()
{
var x=document.forms["signup"]["firstName"].value;
var y=document.forms["signup"]["lastName"].value;
var z=document.forms["signup"]["emailAddress"].value;
var atpos=z.indexOf("@");
var fname;
var sname;
var email;
/* Validate first name */
if (x==null || x=="")
{
document.getElementById("inactiveErrorFname").id = "activeErrorFname";
fname = "true";
}
/* Validate Surname */
if (y==null || y=="")
{
document.getElementById("inactiveErrorSname").id = "activeErrorSname";
sname = "true";
}
/* Validate email */
if (atpos<1)
{
document.getElementById("inactiveErrorEmail").id = "activeErrorEmail";
email = "true";
}
if (fname=="true" || sname=="true" || email =="true")
{
return false;
}
}
</script>