HTML表单验证帮助

时间:2012-07-20 08:15:17

标签: javascript html forms validation email

我正在创建一个简单的HTML联系表单,我想验证三个字段;姓名,电子邮件和消息。但是,当涉及到javascript字段验证并希望得到一些帮助时,我不是最聪明的。我目前的表格如下:

<form action="cgi-bin/FormMail.pl" method="post">
<input type="hidden" name="subject" value="From the feedback form" />
<input type="hidden" name="redirect" value="thankyou.html" />
<p>Whatever you want to say here</p>
<p>&nbsp;</p>
<table>
<tr>
<td align="left">Name:</td>
<td><input type="text" name="name" size="30" value="" /></td>
</tr>
<tr>
<td align="left">E-Mail:</td>
<td><input type="text" name="email" size="30" value="" /></td>
</tr>
<tr>
<td align="left">Content:</td>
<td><textarea name="comment" cols="50" rows="5"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td></td>
</tr>
</table>
<input type="hidden" name="redirect" value="thankyou.html" />
</form>

1 个答案:

答案 0 :(得分:0)

供您参考:根据您的需要修改

<script type="text/javascript">
function validateform()
{
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
  {
  alert("Name Is Blank");
  return false;
  }

var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("invalid e-mail address");
  return false;
  }

var x=document.forms["myForm"]["comment"].value;
if (x==null || x=="")
  {
  alert("Comment is blank");
  return false;
  }
}
</script>


<form name="myForm" action="cgi-bin/FormMail.pl" method="post" onsubmit="return validateform()">
<input type="hidden" name="subject" value="From the feedback form" />
<input type="hidden" name="redirect" value="thankyou.html" />
<p>Whatever you want to say here</p>
<p>&nbsp;</p>
<table>
<tr>
<td align="left">Name:</td>
<td><input type="text" name="name" size="30" value="" /></td>
</tr>
<tr>
<td align="left">E-Mail:</td>
<td><input type="text" name="email" size="30" value="" /></td>
</tr>
<tr>
<td align="left">Content:</td>
<td><textarea name="comment" cols="50" rows="5"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td></td>
</tr>
</table>
<input type="hidden" name="redirect" value="thankyou.html" />
</form>