简体   繁体   中英

check if textbox contain string or not

I want to check if there is string in textbox or not if there is a text in it nd it's not string display error message i tried this code but when i enter string in the textbox error message display

html code:

  <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> 

behind code:

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();
            }

        }

You could try using a regex validator:

    <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]+"/>

I'll note this is only tested with English characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM