Regular Expression Validator in C#


Here is the input validation using Regular Expression Validator in Code behind (C#).

See the below code:

.aspx page

  Input <asp:TextBox ID="txtCheckValidation" runat="server">asp:TextBox><br />
  <asp:Button ID="btnValidate" runat="server" Text="Validate" onclick="btnValidate_Click" /><br />
  <asp:Label ID="lblDisplay" runat="server">asp:Label>

.aspx.cs page

Use namespace as

using System.Text.RegularExpressions;

On Button Click event Write the below code:

Here are the different - different types of expression I have tried, you can do it your way also..

protected void btnValidate_Click(object sender, EventArgs e)
    {
        //For Email
        //Regex regExpression = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
      
        //Matches the beginning (^  ) of the character string
        //Regex regExpression = new Regex(@"^A");

        //Matches any single character which is between brackets (e.g.,v,e or d)
        //Regex regExpression = new Regex(@"[ved]");

        //Matches any characters not between the range of characters between brackets and separated by the dash (e.g., not within a through d)
       // Regex regExpression = new Regex(@"[^a-d]");

        //for Telephone
        Regex regExpression = new Regex(@"[d][10]");

        if (!regExpression.IsMatch(txtCheckValidation.Text))
        {
            lblDisplay.Text = "Huhh..it's not matching...";

        }
        else
        {
            lblDisplay.Text = "Yeppi..it's matching...";
        }

    }

Comments