今天在网上看到了一个密码验证的例子,感觉很好,收藏起来以便以后的学习。 这个是前台: <div> 密码:<asp:TextBox runat="server" ID="txtPassword" /> <asp:Button runat="server" ID="btnConfirm" Text="确定" OnClick="btnConfirm_Click" /> <br /> <asp:Label ID="lblNotify" runat="server" Text="Label"></asp:Label></div> 这个是后台: using System; using System.Data; using System.Configuration; using System.Collections; 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; using System.Text.RegularExpressions; using System.Text; public partial class BuildPassword : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { txtPassword.Text = buildPasswordString(9); } } protected void btnConfirm_Click(object sender, EventArgs e) { string re = "^[0-9a-zA-Z!/"#$%&()*+-./:;<=>?@[//]^_'{|}]{9,}$"; if (!Regex.Match(txtPassword.Text.Trim(), re).Success) { lblNotify.Text = "密码格式不符合条件!"; } else { lblNotify.Text = ""; } } private string buildPasswordString(int length) { string dic = "abcdefg!@#$%^&*()_+=0123456789"; int dicLength = dic.Length; StringBuilder sb = new StringBuilder(9); Random rd = new Random(); for (int i = 0; i < length; i++) { int index = rd.Next(0, dicLength); sb.Append(dic[index]); } return sb.ToString(); } } 这个例子比较好。适合自动生成密码,还有验证输入密码。