检查文本框是否包含字符串

时间:2016-04-02 15:30:01

标签: c# asp.net

我想检查文本框中是否有字符串,如果有文本,并且它不是字符串显示错误消息我试过这段代码但是当我在文本框中输入字符串错误信息显示

html代码:

 <label for="edit-submitted-name">First Name </label>
<asp:TextBox ID="txtfirstname" runat="server" CssClass="form-text" size="60" maxlength="128"></asp:TextBox>
    <asp:CompareValidator ID="cvfirstname" 
        runat="server" ErrorMessage="Must be letters" 
        ControlToValidate="txtfirstname" ForeColor="#db0d15" Type="String"></asp:CompareValidator>

代码背后的

protected void btnsave_Click(object sender, EventArgs e)
        {

            using (DataClasses1DataContext sdc = new DataClasses1DataContext()) {


                    Professor_Dim prof = sdc.Professor_Dims.SingleOrDefault(x => x.P_ID ==Convert.ToInt16(Server.UrlDecode(Request.QueryString["id"])));
                if (!string.IsNullOrEmpty(txtfirstname.Text))
                    prof.P_Fname = txtfirstname.Text;
                if (!string.IsNullOrEmpty(txtlastname.Text))
                    prof.P_Lname = txtlastname.Text;
                if (!string.IsNullOrEmpty(txtemail.Text))
                    prof.P_Email = txtemail.Text;
                if (!string.IsNullOrEmpty(txtaddress.Text))
                    prof.P_Address = txtaddress.Text;
                if (!string.IsNullOrEmpty(txtphone.Text))
                    prof.P_Phone = txtphone.Text;

                if(Male.Checked == true)
                {
                    prof.P_Gender = Male.Text;
                }
                else if (Female.Checked == true)
                {
                    prof.P_Gender = Female.Text;
                }

                if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0)
                {
                    string fileName = FileUpload1.FileName;
                    byte[] fileByte = FileUpload1.FileBytes;
                    Binary binaryObj = new Binary(fileByte);
                    prof.P_Image = binaryObj;
                }
                sdc.SubmitChanges();
            }

        }

1 个答案:

答案 0 :(得分:2)

您可以尝试使用正则表达式验证程序:

    <asp:TextBox ID="txtfirstname" runat="server" CssClass="form-text" size="60" maxlength="128"></asp:TextBox>
     <asp:RegularExpressionValidator ID="regexfirstName" runat="server"     
                                ErrorMessage="Must be Letters" 
                                ControlToValidate="txtfirstname" ForeColor="#db0d15" 
                                ValidationExpression="[a-zA-Z]+"/>

我注意到这只是用英文字符测试的。

相关问题