19.5. Using the RegularExpressionValidator

NOTE

A word of warning about this section: regular expressions are weird and extremely geeky. Here's one that might scare you away:

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

Microsoft supplies the preceding example with the RegularExpressionValidator control to verify (and enforce) the format of an e-mail address. Some of us find the rules of the Klingon language (of Star Trek fame) easier to grasp than the syntax in regular expressions.

The idea of regular expressions is that you create groups of rules that match or don't match characters at the beginning, middle, and end of a string. Sometimes, a regular expression limits the number of characters; sometimes, it requires a certain number of characters; and other times, it doesn't matter.

19.5.1. Testing for one, two, or three numbers

Many books and Web sites are dedicated to regular expressions and many tools can help you assemble them. For your purposes, assume that you figured out — or someone sent you — the following regular expression that checks the validity of an Item ID. The Item ID starts with a digit and ends with a digit. It can have one, two, or three digits but no other characters. Here's the regular expression:

^[0-9]{1,3}$

Follow these steps to implement the preceding regular expression in a RegularExpressionValidator control:

  1. Add an ASP.NET TextBox control and Button control to the page.

  2. From the Validation category of the Toolbox, add a RegularExpressionValidator ...

Get ASP.NET 3.5 For Dummies® 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.