Recipe 5.41. Using Regular Expressions to Validate Data


You need to validate string data entered by a user to ensure it meets defined criteria.


Sample code folder: Chapter 05\RegexValidate

Use a regular expression to check the string to make sure it matches the type of data expected.


The 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 = "" MsgBox(testString & Space(3) & _    Regex.  IsMatch(testString, emailPattern)) testString = "" 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 addresses

Figure 5-49. A string that fails the regular expression test designed to validate it as a legal email address

See Also

Recipe 5.22 also discusses data validation.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: