This tutorial will show you how to use the RegularExpressionValidator control using ASP.NET 2.0 and C#.NET

The .NET Framework offers a number of controls that simplifies the process of validating user input on a web form. One such control is the RegularExpressionValidator. This control allows you to specify an arbitrary regular expression to validate the input to any one control.

To perform RegEx validation using this control we do not need to be using any extra namespaces. All we need to do is add a RegularExpressionValidator to the web form. We’ll put our code in the btnSubmit_Click() event.

When the btnSubmit_Click() event fires it sets the ValidationExpression expression property of the validator to match any decimal number with an optional negative or postive sign in front of it. After clicking the Submit button, the user will be notified when they have not entered a valid decimal number in the textbox.

Note that we must set the ControlToValidate property of the validator at design time to txtDec. Without setting this property you will receive a run-time exception.

We have two textboxes, a submit button, and a label on the front end for user interaction. The front end .aspx page looks something like this:

The flow for the code behind page is as follows:

Download Source Files