驗證碼經常在用戶提交數據的時候,防止惡意頻繁提交數據,確保數據庫的安全性;在ASP.Net中有多種方法可以生成驗證碼,一般是生成圖像的形式,然後用Session對象保存。。。。下面是我自己所采用的一種方法,比較簡單,希望對大家有所幫助,有誤的地方還望大家指正
1.前台代碼
<tr>
<td > 驗證碼</td>
<td >
<asp:TextBox ID="txtValidateCode" runat="server" Height="15px" Width="137px"></ASP:TextBox></td>
<td >
<asp:Label ID="lbValidate" runat="server" Text="Label" Font-Bold="true" Font-Size="14" Width="54px"></ASP:Label>
</td>
</tr>
2.後台代碼
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.txtPwd.Attributes.Add("value", Request["txtPwd"]); //提交後密碼保存
string VNum = GenerateRandom(4); //產生驗證碼
lbValidate.Text = VNum; //把驗證碼的值給lable
}
private static char[] constant =
{
''0'',''1'',''2'',''3'',''4'',''5'',''6'',''7'',''8'',''9'',
''a'',''b'',''c'',''d'',''e'',''f'',''g'',''h'',''i'',''j'',''k'',''l'',''m'',''n'',''o'',''p'',''q'',''r'',''s'',''t'',''u'',''v'',''w'',''x'',''y'',''z'',
''A'',''B'',''C'',''D'',''E'',''F'',''G'',''H'',''I'',''J'',''K'',''L'',''M'',''N'',''O'',''P'',''Q'',''R'',''S'',''T'',''U'',''V'',''W'',''X'',''Y'',''Z''
};
//產生驗證碼
public static string GenerateRandom(int Length)
{
System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);
Random rd = new Random();
for (int i = 0; i < Length; i++)
{
newRandom.Append(constant[rd.Next(62)]);
}
return newRandom.ToString();
}
}
3.前台客戶端驗證
<script language="Javascript">
function Check_Validate()
{
var str=document.getElementById("lbValidate").outerText;
var pos = document.getElementById("txtValidateCode").value;
var name=document.getElementById("txtName").value;
var passWord=document.getElementById("txtPwd").value;
//var str = document.all("lbValidate").outerText;
//var pos = document.all("txtValidateCode").value;
if(name=="")
{
alert("請輸入用戶名!");
return false;
}
if(passWord=="")
{
alert("請輸入密碼!");
return false;
}
if(pos=="")
{
alert("請輸入驗證碼!");
return false;
}
if (str!=pos)
{
alert("驗證碼錯誤!請注意字母的大小寫!");
return false;
}
else
{
return true;
}
}
</script>
最後在提交按鈕中添加客戶端驗證 OnClIEntClick="Check_Validate()" 即可