<table id="tab" border="0" cellpadding="0" cellspacing="0" style="width: 182px"> <tr> <td style="width: 276px"> <span style="font-size: 10pt">密码强度:</span></td> <td id="r" style="width: 100px"> <asp:Label ID="labEbb" runat="server" Text="弱" Width="18px" Font-Size="12px"></asp:Label></td> <td style="width: 92px"> <asp:Label ID="labStrong" runat="server" Text="强" Width="18px" Font-Size="12px"></asp:Label></td> <td style="width: 106px"> </td> </tr> </table> 判断是否注册: 前台代码: <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <table border="0" cellpadding="0" cellspacing="0" style="width: 477px; height: 48px;"> <tr> <td style="width: 88px; height: 24px; text-align: right"> <span style="font-size: 10pt">会 员 名: </span> </td> <td style="height: 24px; text-align: left; width: 509px;" colspan="2"> <asp:TextBox onFocus="tName();" ID="txtName" runat="server" Width="89px" AutoPostBack="True" OnTextChanged="txtName_TextChanged"></asp:TextBox><span style="color: #ff0000">*</span><asp:RequiredFieldValidator ID="rfvName" runat="server" ErrorMessage="用户名不能为空" Width="1px" ControlToValidate="txtName">*</asp:RequiredFieldValidator> <asp:Label ID="labUser" runat="server" Text="只能输入数字、字母、下划线" Width="159px" Font-Size="12px"></asp:Label> <asp:Label ID="labIsName" runat="server" Font-Size="12px"></asp:Label></td> </tr> </table> </ContentTemplate> </asp:UpdatePanel> 后台代码: protected bool isName() { //创建一个布尔型变量并初始化为false; bool blIsName = false; //创建SQL语句,该语句用来判断用户名是否存在 string sqlSel = "select count(*) from tb_userInfo where userName='" + txtName.Text + "' "; //创建数据库连接 SqlConnection con = new SqlConnection("server=.;database=db_Register;uid=sa;pwd=102545;"); //打开数据库连接 con.Open(); //创建SqlCommand对象 SqlCommand com = new SqlCommand(sqlSel, con); //判断ExecuteScalar方法返回的参数是否大于0,大于表示用户名已存在 if (Convert.ToInt32(com.ExecuteScalar()) > 0) { blIsName = true; } else { blIsName = false; } //返回布尔值变量 return blIsName; } protected bool isNameFormar() { //创建一个布尔型变量并初始化为false; bool blNameFormar = false; //设置正则表达式 Regex re = new Regex("^\\w+$"); //使用Regex对象中的IsMatch方法判断用户名是否满足正则表达式 if (re.IsMatch(txtName.Text)) { //设置布尔变量为true blNameFormar = true; //设置label控件的颜色 labUser.ForeColor = System.Drawing.Color.Black; } else { labUser.ForeColor = System.Drawing.Color.Red; blNameFormar = false; } //返回布尔型变量 return blNameFormar; } protected void txtName_TextChanged(object sender, EventArgs e) { //判断用户名是否为空 if (txtName.Text == "") { //使用Label控件给出提示 labIsName.Text = "用户名不能为空"; //设置Label控件的颜色 labIsName.ForeColor = System.Drawing.Color.Red; } else { //调用自定义isNameFormar方法判断用户名是否满足格式要求 if (isNameFormar()) { //调用isName自定义方法判断用户名是否已注册 if (isName()) { labIsName.Text = "用户名已存在!"; labIsName.ForeColor = System.Drawing.Color.Red; } else { labIsName.Text = "可以注册!"; labIsName.ForeColor = System.Drawing.Color.Blue; } } else { labIsName.Text = ""; } } }