Utilize Built-in Validation Controls on Your Web Forms...
By: John Kilgo Date: December 3, 2002 Download the code.


The following program demonstrates the use of several of the .Net validation controls. The first two text boxes utilize the RequiredFieldValidator control. There is no particular reason for these fields to be required - they just demonstrate use of the control. The use of RequiredFieldValidators is very straight forward, so I won't comment much on them here except to point out one thing common to all validation controls. They all contain a property of "ControlToValidate". This tells the control which textbox on which to perform the validation.

The first text box (txtDate) also contains a CompareValidator. As suggested by its name, this control compares the textbox value to some other specified value or control. In the case we want a date entered so we set the Operator property equal to "DataTypeCheck" and the Type property to "Date". We have now instructed the control to make sure a date in the form MM/DD/YYYY or MM-DD-YYYY is entered in txtDate.

For the next text box (txtAmount) we perform a different type of comparison. Here we want an amount that is greater than $1,000.00 (don't enter the $ sign in the textbox). Here we set the Operator property to "GreaterThan" and the Type property to "Currency". We also set the ValueToCompare property to 1,000.00. Any input under 1,000 should fail the validation.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FormValidation</title>
<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
<meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body>
<form id="Form1" method="post" runat="server">
<h3>Validation Examples</h3>
<table>
  <tr>
    <td>Enter a Date:</td>
    <td><asp:textbox runat="server" id="txtDate"></asp:textbox></td>
    <td>
      <asp:RequiredFieldValidator runat="server" id="rfvDate"
          ControlToValidate="txtDate" display="dynamic">
          A date value is required.
      </asp:RequiredFieldValidator>
      <asp:CompareValidator runat="server" id="cvDate"
          ControlToValidate="txtDate" display="dynamic"
          Operator="DataTypeCheck" Type="Date">
          Date must be in the format MM/DD/YYYY or MM-DD-YYYY.
      </asp:CompareValidator>
    </td>
  </tr>
  <tr>
    <td>Enter a Value greater than $1,000.00:</td>
    <td><asp:textbox runat="server" id="txtAmount"></asp:textbox></td>
    <td>
      <asp:RequiredFieldValidator runat="server" id="rfvAmount"
          ControlToValidate="txtAmount" display="dynamic">
          An amount is required.
      </asp:RequiredFieldValidator>
      <asp:CompareValidator runat="server" id="cvAmount" ValueToCompare="1,000.00"
          ControlToValidate="txtAmount" display="dynamic"
          Operator="GreaterThan" Type="Currency">
          Amount must be greater than $1,000.00.
      </asp:CompareValidator>
    </td>
  </tr>
The next four textboxes all have associated RegularExpressionValidator controls. Regular expressions, if you've never used them before, perform pattern matching. This means that you can compare the format or pattern of an entry in a textbox to some known pattern or format that you want enforced.

Common patterns are "123-45-6789" (the pattern is three numbers followed by a hyphen, two numbers followed by a hyphen, followed by four numbers) for social security numbers, "webmaster@dotnetjohn.com" (the pattern is a string of characters followed by the "@" sign, followed by a string of characters followed by a peroid, followed by a two or three character string) for email addresses, "32309" or "32309-1234" for zip codes, and 850-123-4567 for a telephone number, etc.

Since, in my opinion, regular expressions are difficult to understand and hard to remember, we will tackle these controls one at a time. (A full discussion of regular expressions is well beyond the scope of this article, or even a small book for that matter!)

First the email textbox. The regular expression in use here is "^[\w-\.]+@([\w-]+\.)+[\w-]{2,3}$". Notice that the ugly string begins with a caret (^) and ends with a $ sign. The caret essentially means "the string pattern begins here". The $ sign means "the string pattern ends here". The [ ] brackets are used to indicate a range of values. [1-10], for example means any number between one and ten. Some characters have special meanings and must be escaped using the "\" sign.

The first bracketed sequence in our email pattern is "[\w-\.]". \w means any alphanumeric sequence and includes the underscore (_) character. This means that \w includes a-z, A-Z, 0-9 and _. But since hyphens (-) and periods (.) are also legal in an email address we must include them also (. is a special character and must be escaped using the \ character).

The next character in our string is a + sign. This means that the preceeding string of legal characters can appear any number of times.

Next in line is the @ character. That simply means that the @ sign must appear (once) in the email address. Thus far we have covered the your-name@ portion of the email address. The rest of our string covers what comes after the @ sign.

The next portion of the regular expression is "([\w-]+\.)+". The parentheses are a way of grouping expressions. The quoted string means any alphanumeric characters (including the underscore character), plus the hyphen, can be repeated any number of times (the first + sign does that) and finally the . can follow the group of other legal characters. The final + sign means that everything to the left can be repeated any number of times. That means that something like yourdomain. is legal and also abc.state.fl. is legal.

The final part of the string is "[\w]{2,3}". This covers the ending two or three characters of the email address. The [\w] once again means any alphanumeric string. The {2,3} means that the final portion of the address must be exactly two or three characters long. {} are used to specify an exact number of times a legal character can appear. We set it to two or three since our address could end with ".us" or ".com", for example.

There are strengths and weaknesses to the regular expression discussed above. The ending, for example would allow for a .cxy extension. That, at this moment, is not a legal domain name extension, but our validator will except it. We could instead include the extensions such as ".com", ".net", ".us", etc., but as new extensions are added by the governing bodies our validator would begin to fail and we would have to keep updating it as each new extension comes along.

  <tr>
    <td>E-Mail</td>
    <td><asp:textbox runat="server" id="email" columns="25"></asp:textbox<</td>
    <td>
      <asp:RegularExpressionValidator runat="server" id="revEmail"
          ControlToValidate="email" display="dynamic"
          ValidationExpression="^[\w-\.]+@([\w-]+\.)+[\w-]{2,3}$">Must be 'AAA...@AAA.AA(A)'
      </asp:RegularExpressionValidator>
    </td>
  </tr>
The next control to be validated using regular expressions is the telephone number textbox. Telephone numbers could be formatted several different ways. For this example I chose to require the 999-999-9999 format (requiring a three digit area code, followed by a hyphen then a three digit number, followed by a hypen and and a four digit number.

The regular expression for this format is "^[2-9]\d{2}-\d{3}-\d{4}$". Since US telephone area codes cannot begin with a 0 or 1, we use the bracketed [2-9] to require that a 2 through 9 be the first number of the area code. "\d" means any numeric digit. This means that the area code portion must contain exactly two more digits. The \d{2] enforces this requirement. The rest of the expression is straight forward: a hyphen followed by excactly three digits followed by another hyphen and exactly four more digits.

  <tr>
    <td>Telephone</td>
    <td><asp:textbox runat="server" columns="15" id="phone"></asp:textbox></td>
    <td>
      <asp:RegularExpressionValidator runat="server" id="revPhone"
          ControlToValidate="phone" display="dynamic"
          ValidationExpression="^[2-9]\d{2}-\d{3}-\d{4}$">Must be 'NNN-NNN-NNNN'
      </asp:RegularExpressionValidator>
    </td>
  </tr>
The next expression covers the Social Security Number. Compared to what we have seen so far, the SSAN expression,
"^\d{3}-\d{2}-\d{4}$" is very easy to understand. Three numerics followed by a hyphen, two numerics followed by a hypen, follewed by four numerics. Actually, Social Security Numbers are a little more restricted than the above. There are restrictions on the first number and a handful of prohibited numbers. I will leave it to you to discover the restrictions on your own.
  <tr>
    <td>Social Security Number</td>
    <td><asp:textbox runat="server" columns="9" id="ssan"></asp:textbox></td>
    <td>
      <asp:RegularExpressionValidator runat="server" id="revSSAN"
          ControlToValidate="ssan" display="dynamic"
          ValidationExpression="^\d{3}-\d{2}-\d{4}$">Must be 'NNN-NN-NNNN'
      </asp:RegularExpressionValidator>
    </td>
  </tr>
The final expression to be covered is one for a US zip code. I decided to accept either a five digit code, like "12345", or a zip+four code like "12345-1234". The reqular expression used is "^\d{5}-\d{4}|\d{5}$". This expression introduces the pipe ("|") character. The pipe is a logical OR. So reading the expression from the left we see that we must have exactly five digits followed by a hyphen followed by exactly four digits, OR, just exactly five digits.
  <tr>
    <td>Zip Code</td>
    <td><asp:textbox runat="server" columns="10" id="zip"></asp:textbox></td>
    <td>
      <asp:RegularExpressionValidator runat="server" id="revZip"
          ControlToValidate="zip" display="dynamic"
          ValidationExpression="^\d{5}-\d{4}|\d{5}$">Must be 'NNNNN' or 'NNNNN-NNNN'
      </asp:RegularExpressionValidator>
    </td>
  </tr>
</table>
<br>
<asp:button id="btnValidate" runat="server" text="Validate"></asp:button>
</form>
</body>
</html>
Conclusion: In this article you have seen how to implement the fairly simple RequiredFieldValidator, the only slightly more complicated CompareValidator, and the much more complex ReqularExpressionValidator. To learn more about regular expressions in .Net you can click Here.

To run the example program please click here. To download the program you may click Here.