ProblemYou need to validate string data entered by a user to ensure it meets defined criteria. SolutionSample code folder: Chapter 05\RegexValidate Use a regular expression to check the string to make sure it matches the type of data expected. DiscussionThe Internet is a good place to find a wide range of regular expressions to validate strings using specific rules, and this recipe won't attempt to list them all. Instead, the following code, which validates a String as an email address, demonstrates a specific example to show you the general technique involved: Imports System.Text.RegularExpressions ' …Later, in a method… Dim testString As String Dim emailPattern As String = _ "^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@" & _ "([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$" testString = "johndoe@nowhere.com" MsgBox(testString & Space(3) & _ Regex. IsMatch(testString, emailPattern)) testString = "john@doe@mybad.com" MsgBox(testString & Space(3) & _ Regex.IsMatch(testString, emailPattern)) This regular expression checks a string to see if it is a valid email address. As shown in Figures 5-48 and 5-49, the first string passes the test, but the second has a problem. In general, the IsMatch() method returns TRue if the string matches the criteria defined in the regular expression and False if it fails the test. Figure 5-48. A string that passes the regular expression test for valid email addressesFigure 5-49. A string that fails the regular expression test designed to validate it as a legal email addressSee AlsoRecipe 5.22 also discusses data validation. |