由于在表单中使用 value="" 属性,表单验证不起作用。任何人都可以建议我使用当前验证代码在表单中使用 value="" 属性来验证表单的任何方法。
HTML 代码-
<form action="email.php" method="post" name="contactForm" id="contactForm" onsubmit="return validateForm();">
<input type="text" onfocus="if(this.value == 'Name'){this.value = '';}" onblur="if(this.value == ''){this.value='Name';}" id="Name" value="Name" name="name">
<input type="text" onfocus="if(this.value == 'Company'){this.value = '';}" onblur="if(this.value == ''){this.value='Company';}" id="Company" value="Company" name="company">
<input type="text" onfocus="if(this.value == 'Email'){this.value = '';}" onblur="if(this.value == ''){this.value='Email';}" id="Email" value="Email" name="email">
<input type="text" onfocus="if(this.value == 'Phone'){this.value = '';}" onblur="if(this.value == ''){this.value='Phone';}" id="Phone" value="Phone" name="phone">
<span>
<input type="text" onfocus="if(this.value == 'Geo Targeting'){this.value = '';}" onblur="if(this.value == ''){this.value='Geo Targeting';}" id="GeoTargeting" value="Geo Targeting" name="geo_targeting">
<input type="text" onfocus="if(this.value == 'Web Site'){this.value = '';}" onblur="if(this.value == ''){this.value='Web Site';}" id="WebSite" value="Web Site" name="website">
<textarea onfocus="if(this.value == 'Message'){this.value = '';}" onblur="if(this.value == ''){this.value='Message';}" id="Message" name="message">Message</textarea>
<input class="sendBtn" name="submit" type="submit" value="Send" />
</span>
</form>
Javascript代码-
<script language="javascript" type="text/javascript">
function validateForm() {
var x=document.forms["contactForm"]["name"].value;
if (x==null || x=="") {
alert("Name must be filled out");
return false;
}
var x=document.forms["contactForm"]["company"].value;
if (x==null || x=="") {
alert("Company Name must be filled out");
return false;
}
var x=document.forms["contactForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Email must be filled out/Not a valid e-mail address");
return false;
}
var x=document.forms["contactForm"]["message"].value;
if (x==null || x=="") {
alert("Message must be filled out");
return false;
}
}
</script>