Validate Input with a Regular Expression

Problem

You want to validate a common user-submitted value contained in a string, such as an e-mail address, date, or user name.

Solution

Create the System.Text.RegularExpressions.Regex class with the appropriate regular expression, and call the IsMatch method with the value you want to test. Make sure to include the $ and ^ characters in your expression so that you match the entire string.

Discussion

Although creating a regular expression can be difficult, applying one is not. You simply need to create a Regex instance, supply the regular expression in the constructor, and then test for a match. The following code example verifies an e-mail address using a regular expression from Table 1-2. In order for it ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.