2.5 Validate Input Using Regular Expressions


Problem

You need to validate that user input or data read from a file has the expected structure and content. For example, you want to ensure that a user enters a valid IP address, telephone number, or e-mail address.

Solution

Use regular expressions to ensure that the input data follows the correct structure and contains only valid characters for the expected type of information.

Discussion

When a user inputs data to your application or your application reads data from a file, it's good practice to assume that the data is bad until you have verified its accuracy. One common validation requirement is to ensure that data such as e- mail addresses, telephone numbers, and credit card numbers follow the pattern and content constraints expected of such data. Obviously you can't be sure the data entered is valid until you use it, or compare it against values that are known to be correct, but ensuring the data has the correct structure and content is a good first step to determining whether the input is accurate. Regular expressions provide an excellent mechanism for evaluating strings for the presence of patterns; you can use this to your advantage when validating input data.

The first thing you must do is figure out the regular expression syntax that will correctly match the structure and content of data you are trying to validate. This is by far the most difficult aspect of using regular expressions. Regular expressions are constructed from two types of elements: literals and metachar acters. Literals represent specific characters that appear in the pattern you want to match. Metacharacters provide support for wildcard matching, ranges, grouping, repetition, conditionals, and other control mechanisms. A full discussion of regular expression syntax is beyond the scope of this book, but Table 2. 2 describes some of the more commonly used elements. (Consult the .NET SDK documentation for a full description of regular expressions.)

Table 2.2: Commonly Used Regular Expression Metacharacter Elements

Element

Description

.

Specifies any character except a new line (\n)

\d

Specifies any decimal digit

\D

Specifies any nondigit

\s

Specifies any white-space character

\S

Specifies any non-white-space character

\w

Specifies any word character

\W

Specifies any nonword character

^

Specifies the beginning of the string or line

\A

Specifies the beginning of the string

$

Specifies the end of the string or line

\z

Specifies the end of the string

Matches one of the expressions separated by the vertical bar; for example AAAABAABB will match one of AAA, ABA, or ABB. (The expression is evaluated left to right.)

[abc]

Specifies a match with one of the specified characters; for example [AbC] will match A, b, or C but no other character

[^abc]

Specifies a match with any one character except those specified; for example [^AbC] will not match A, b, or C but will match B, F and so on

[a-z]

Specifies a match with any one character in the specified range; for example [A-C] will match A, B, or C

( )

Identifies a subexpression so that it's treated as a single element by the regular expression elements described in this table

?

Specifies one or zero occurrences of the previous character or subexpression; for example A?B matches B, AB, but not AAB

*

Specifies zero or more occurrences of the previous character or subexpression; for example, A*B matches B, AB, AAB, AAAB, and so on

+

Specifies one or more occurrences of the previous character or subexpression; for example, A+B matches AB, AAB, AAAB, and so on, but not B

{n}

Specifies exactly n occurrences of the preceding character or sub-expression; for example, A{2} matches only AA

{n,}

Specifies a minimum of n occurrences of the preceding character or subexpression; for example, A{2,} matches AA, AAA, AAAA and so on, but not A

{n, m}

Specifies a minimum of n and a maximum of m occurrences of the preceding character; for example, A{2,4} matches AA, AAA, and AAAA but not A or AAAAA

The more complex the data you are trying to match, the more complex the regular expression syntax becomes. For example, ensuring that input contains only numbers or is of a minimum length is trivial, but ensuring a string contains a valid URL is extremely complex. Table 2.3 shows some example regular expressions that will match against commonly required data types.

Table 2.3: Commonly Used Regular Expressions

Input Type

Description

Regular Expression

Numeric input

The input consists of one or more decimal digits; for example "5", or "5683874674".

^\d+$

PIN

The input consists of four decimal digits; for example "1234".

^\d{4}$

Simple password

The input consists of between 6 through 8 characters; for example "ghtd6f" or "b8c7hogh".

^\w{6,8}$

Credit card number

The input consists of data that matches the pattern of most major credit card numbers; for example "4921835221552042" or "4921-8352- 2155-2042".

^\d{4}-?\d{4}-?\d{4}- ?\d{4}$

E-mail address

The input consists of an Internet e-mail address. The [\w-]+ expression indicates that each address element must consist of one or more word characters or hyphens; for example some-body@adatum.com.

^[\w-]+@([\w- ]+\.)+[\w-]+$

HTTP or HTTPS URL

The input consists of an HTTP-based or HTTPS-based URL, for example http://www.microsoft.com.

^https?://([\w- ]+\.)+[\w-]+(/[\w- ./ ?%=]*)?$

Once you know the correct regular expression syntax, create a new System.Text.RegularExpressions.Regex object passing a string containing the regular expression to the Regex constructor. Then call the IsMatch method of the Regex object and pass the string that you want to validate; IsMatch returns a bool indicating whether the Regex object found a match in the string. The regular expression syntax determines whether the Regex will match only against the full string or whether it will match against patterns contained within the string. (See the ^, \A, $, and \z entries in Table 2.2.)

The ValidateInput method shown here tests any input string to see if it matches a specified regular expression.

 public static bool ValidateInput(string regex, string input) {     // Create a new Regex based on the specified regular expression.     Regex r = new Regex(regex);     // Test if the specified input matches the regular expression.     return r.IsMatch(input); } 

You can use the Regex object repeatedly to test multiple strings, but you can't change the regular expression tested for by a Regex object; you must create a new Regex object to test for a different pattern. Because the ValidateInput method creates a new Regex each time it's called, instead you could use a static overload of the IsMatch method, as shown in the following variant of the ValidateInput method.

 public static bool ValidateInput(string regex, string input) {     // Test if the specified input matches the regular expression.     return Regex.IsMatch(input, regex); } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net