Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

Data Validation With Regular Expressions In ASP.NET

Regular expressions are powerful way to validate data. If you just need to check something like if input string has no more than 5 characters and contains only digits you can do that easily using Int32.TryParse and String.Length methods. Regular expressions become more useful when your data are more complex.

Programmers often avoid learning of regular expressions because they look difficult on the first look. But, if you need to validate more demanding pattern, like e-mail address, URL or credit card number, classic approach with string manipulation will take significant time and result with a long code. Solution that uses regular expression is usually much shorter to write and executes faster.

In general, there are two methods to validate data in ASP.NET applications:

1. Web form data validation - You need to validate every input that comes from user. If user fills and submits web form, you need to check if inserted data are formatted in certain way. To perform validation with regular expressions on ASP.NET web form, use RegularExpressionValidator control.

2. Validation of data that come from other sources (cookies, query strings, web services etc.). In this case, you can validate data using Regex class from System.Text.RegularExpressions namespace.

ASP.NET form validation with RegularExpressionValidator control

ASP.NET provides few validation controls that can be used to check user input. Common validation controls, like RequiredFieldValidator, RangeValidator or CompareValidator could be used for simple tasks like check for required values, ranges and comparisons. More about these ASP.NET validation controls you can read in Validation in ASP.NET tutorial. For more complex tasks we need to use RegularExpressionValidator control.

Any data validation in ASP.NET can be performed with client and server side code. Client side validation works faster, since there is no need to send request to server. So, to provide better user experience, you should consider client side validation which executes as JavaScript client code. Server side validation is also important because of security reasons. Client side validation could be avoided and also some visitors have JavaScript disabled.

Let's say you have an feedback web form with few text boxes and button to send a message, like in image bellow:

Regular Expression contact form

You require valid e-mail from user because otherwise you can't answer to submitted message. Writing function in C# or VB.NET to check if email is valid would require complex string manipulation. Fortunately, using regular expressions this task is simple.

Drag RegularExpressionValidator control from toolbox (it is located under Validation tab) and place it on web form, near the email text box, named tbEmail. Now, we need to set few properties. Like on next image marked red, set ControlToValidate property of RegularExpressionValidator control to tbEmail, in ErrorMessage property write appropriate message if user makes mistake.

RegularExpressionValidator Properties

To enable client side validation, EnableClientScript property should be True (it is already true by default).

Now, we need to set ValidationExpression property to appropriate regular expression.You can write expression directly or press small button on right side to get standard expressions, like marked on next image:

ValidationExpression property

Regular Expression Editor window will pop up, with a list of common regular expressions. Select "Internet e-mail address" and click OK.

Regular Expression Editor

Now, ValidationExpression property is set to \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*. This expression doesn't work well for empty string or if user writes only spaces. To cover these cases, add RequiredFieldValidator control next to tbEmail. Set ControlToValidate to tbEmail and ErrorMessage property to "Please insert a valid e-mail". Set Display property to dynamic of both RegularExpressionValidator and RequierdFieldValidator controls.

Run application to test how it works. If you try to insert irregular e-mail address, you'll get an info to correct your input.

RegularExpressionValidator output message

As you see, using of RegularExpressionValidator doesn't require writing of server side code. Just set few properties and select regular expression from the list. If list doesn't contain regular expression for your problem, you can write it manually in ValidationExpression property. For security reasons, don't forget to include server side validation on "Send Message" button click using Page or Validator's IsValid property.

Data validation using Regex class

RegularExpressionValidator can validate only data that come from web form. If you need to validate data from other sources like query string, XML, web service, cookies etc., you can do it using Regex class from System.Text.RegularExpressions namespace. Regex class is immutable (read-only), thread safe and can be shared between threads.

Here is an example that validates e-mail address. Unlike first example, this time data come from query string so we can't use RegularExpressionValidator. But, Regex comes to rescue!

[ C# ]

using System;

// We need this namespace to work with Regular Expressions
using System.Text.RegularExpressions;

public partial class Contact : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    // Creates Regex instance and set pattern to validate e-mail address
    Regex regEmail = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
 
    // Performs validation of data from query string
    Match matchEmail = regEmail.Match(Request.QueryString["Email"].ToString());
    if (matchEmail.Success)
    {
      // E-mail address is valid, do something with it like store it to database,
      // create automated response etc.
 
    }
    else
    {
      // E-mail is not valid
 
    }
  }
}

[ VB.NET ]

Imports System
 
' We need this namespace to work with Regular Expressions
Imports System.Text.RegularExpressions
 
Partial Class Default2
  Inherits System.Web.UI.Page
 
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ' Creates Regex instance and set pattern to validate e-mail address
    Dim regEmail As Regex = New Regex("\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")
 
    ' Performs validation of data from query string
    Dim matchEmail As Match = regEmail.Match(Request.QueryString("Email").ToString())
    If matchEmail.Success Then
      ' E-mail address is valid, do something with it like store it to database,
      ' create automated response etc.
 
    Else
      ' E-mail is not valid
 
    End If
  End Sub

End Class

Regex class has a number of static methods, so you can perform validation with one line of code, without need to create Regex object to use it. Static solution for problem like above would be:

[ C# ]

using System;
 
// We need this namespace to work with Regular Expressions
using System.Text.RegularExpressions;
 
public partial class Contact : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    // Using static IsMatch method to validate e-mail address
    if (Regex.IsMatch(
      // First parameter is string to be validated
      Request.QueryString["Email"].ToString(),
      // Second parameter is regular expression pattern
      @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
    {
      // If IsMatch returns true e-mail address is valid, do something with it like store it to database,
      // create automated response etc.
 
    }
    else
    {
      // E-mail is not valid
 
    }
  }
}

[ VB.NET ]

Imports System
 
' We need this namespace to work with Regular Expressions
Imports System.Text.RegularExpressions
 
Partial Class Default2
  Inherits System.Web.UI.Page
 
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ' Using static IsMatch method to validate e-mail address
    ' First parameter is string to be validated
    ' Second parameter is regular expression pattern
    If Regex.IsMatch( _
      Request.QueryString("Email").ToString(), _
      "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*") = True Then
      
      ' E-mail address is valid, do something with it like store it to database,
      ' create automated response etc.
 
    Else
      ' E-mail is not valid
 
    End If
  End Sub
End Class

If possible, choose IsMatch method instead of Match. Static method doesn't require creating of Regex object so it provides better performances.

Conclusion

As you see, using of regular expressions to validate data in ASP.NET is relatively simple task. Depending of from where your data come, use RegularExpressionValidator or Regex class. Code is short and most time will probably go on writing regular expression, especially if problem is complex and not standard. There is a big chance that your problem someone already solved, so quick Google search to find regular expression for certain problem is also an option.

Happy coding!


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   Google