Database Search Solution
(New Version) Search Control
Free ASP.NET Controls
ASP.NET Media Player Control
Flash Video Player Control
ASP.NET Telecommute Jobs
Free IP Location Lookup
Test .Net Regular Expressions
CSS/Table/DIV Page Layouts
Article Sites Master List
.NET Windows Forms
General .NET Framework
Accepting Credit Cards
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.
Let's say you have an feedback web form with few text boxes and button to send a message, like in image bellow:
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.
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:
Regular Expression Editor window will pop up, with a list of common regular expressions. Select "Internet e-mail address" and click OK.
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.
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# ]
[ VB.NET ]
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# ]
[ VB.NET ]
If possible, choose IsMatch method instead of Match. Static method doesn't require creating of Regex object so it provides better performances.
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.
comments powered by Disqus