Now let's look at the specific ASP.NET Web server control validators. Remember that these controls all reside in the System.Web.UI.WebControls namespace and they inherit the WebControl base class.
They also have another class called BaseValidator from which they inherit. This class has properties and methods that are common to all validator controls (see Table 8.1).
Note |
Remember and it's worth repeating that inheritance isn't a big word to be afraid of. It's easily understandable. If one object class inherits from another, it gets all of its properties and methods from that class. Each inherited object is a building block that brings its pieces to the receiving object. All methods and properties within an object have either been inherited or have been defined uniquely within the object. |
Property | Description |
---|---|
ControlToValidate | Gets or sets the input web control that the validator is assigned to. |
Display | Gets or sets whether the validation control is displayed and whether its place is held in the HTML. The options are none, static, or dynamic. |
EnableClientScript | Gets or sets a value indicating whether client-side validation is enabled. |
Enabled | Gets or sets a value indicating whether the validator is enabled. |
ErrorMessage | Gets or sets the text for the error message. |
ForeColor | Gets or sets the color of the error message text. The default color is red. |
IsValid | Gets or sets a value that indicates whether the associated input control validates. |
The BaseValidator also has one method called Validate(), which performs the validation on the control. This is handy, and I will show you how to use this method to bring added control to your validation plans.
There is also another class of validators that compare values inherited from an object called the BaseCompareValidator. It only has one additional property called Type, which is described in Table 8.2.
Property | Description |
---|---|
Type | Gets or sets the data type that the values being compared are converted to before the comparison is made. The default is String. |
This property enables you to tell the validator what data type you want to compare. Table 8.3 provides a list of data types that this property can use.
Data Type | Description |
---|---|
String | Specifies a string data type. |
Integer | Specifies a 32-bit signed integer data type. |
Double | Specifies a double precision floating point number data type. |
Date | Specifies a date data type. |
Currency | Specifies a monetary data type. |
Now let's look at the validators themselves. There are very simple validators, such as a RequiredFieldValidator, that just force any type of information to be inserted to more complex validators such as the custom validator that allows you to create custom validation controls.
The RequiredFieldValidator does exactly what you'd expect. It requires something to be input into a field. It has one property, described in Table 8.4.
Property | Description |
---|---|
InitialValue | Gets or sets the value with which the input field is compared. By default it compares to an empty string or nothing, but setting this property causes the validator to compare against the InitialValue property. |
The RequiredFieldValidator has no methods of its own. The following example sets the EnableClientScript="False", which forces server-side validation.
<%@ page language="vb" runat="server"%> <script runat=server> sub Page_Load(sender as Object, e as EventARgs) if (IsPostBack) then Validate() end if end sub </script> <html> <head> <title></title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <asp:TextBox runat="server" /> <asp:RequiredFieldValidator EnableClientScript="false" ControlToValidate="OurTextBox" ErrorMessage="This is a Required Field" runat="server" /> <br> <asp:Button runat="server" text="Submit" /><br> </form> </body> </html>
<%@ page language="c#" runat="server"%> <script runat=server> void Page_Load(Object sender, EventArgs e) { if (IsPostBack) { Validate(); } } </script> <html> <head> <title></title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <asp:TextBox runat="server" /> <asp:RequiredFieldValidator EnableClientScript="false" ControlToValidate="OurTextBox" ErrorMessage="This is a Required Field" runat="server" /><br> <asp:Button runat="server" text="Submit" /><br> <asp:label runat="server" /> </form> </body> </html>
The RangeValidator allows you to compare the input data and validate whether it falls between two values. The two values make up the additional properties of the range validator (see Table 8.5).
Note |
The RangeValidator fails only if the entered data doesn't fit into the range provided. If the field is left blank, this validator will not create an error. If the field being validated is a required field, you must use a RequiredFieldValidator in conjunction with the RangeValidator as well. |
Property | Description |
---|---|
MinimumValue | Gets or sets the minimum value of the validation range. |
MaximumValue | Gets or sets the maximum value of the validation range. |
Remember the Type property from the BaseValidator object? We are going to use that here to change what kind of data is being validated. One text box validates a range based on an integer and the other validates a date range.
<%@ page language="vb" runat="server"%> <script runat=server> sub Page_Load(sender as Object, e as EventArgs) if (IsPostBack) then Validate() end if end sub </script> <html> <head> <title>Validators - Range</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h1>Bulk Ticket Offer</h1> How many tickets (between 20 and 100)<br> <asp:RangeValidator ControlToValidate="OurNumBox" Type="Integer" MinimumValue="20" MaximumValue="100" ErrorMessage="You must pick between 20 and 100" runat="server" /><br> <asp:TextBox runat="server" /><br> Dates: July 1, 2002 - December 31,2002<br> <asp:RangeValidator ControlToValidate="OurDateBox" Type="Date" MinimumValue="7/1/2002" MaximumValue="12/31/2002" ErrorMessage="Show isn't offered on that date." runat="server" /><br> <asp:TextBox runat="server" /> Format: xx/xx/xxxx<br> <asp:Button runat="server" text="Submit" /> </form> </body> </html>
<%@ page language="c#" runat="server"%> <script runat=server> void Page_Load(Object sender, EventArgs e) { if (IsPostBack) { Validate(); } } </script> <html> <head> <title>Validators - Range</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h1>Bulk Ticket Offer</h1> How many tickets (between 20 and 100)<br> <asp:RangeValidator ControlToValidate="OurNumBox" Type="Integer" MinimumValue="20" MaximumValue="100" ErrorMessage="You must pick between 20 and 100" runat="server" /><br> <asp:TextBox runat="server" /><br> Dates: July 1, 2002 - December 31,2002<br> <asp:RangeValidator ControlToValidate="OurDateBox" Type="Date" MinimumValue="7/1/2002" MaximumValue="12/31/2002" ErrorMessage="Show isn't offered on that date." runat="server" /><br> <asp:TextBox runat="server" /> Format: xx/xx/xxxx<br> <asp:Button runat="server" text="Submit" /> </form> </body> </html>
As you can see in Figure 8.2, I have used the RangeValidator to validate two different text boxes containing two different data types.
The CompareValidator can serve two purposes. It can compare the value of a input control against a defined value with a variety of comparison operators. For instance, you can restrict that the input value be less than an certain number. It can also compare the value of two controls against each other. Table 8.6 lists the properties that let you do this.
Property | Description |
---|---|
ControlToCompare | Gets or sets the input control to compare with the input control being validated. |
Operator | Gets or sets the comparison operation to perform. The default is Equal, with additional options being NotEqual, GreaterThan, GreatThanEqual (greater than or equal to), LessThan, and LessThanEqual (less than or equal to). |
ValueToCompare | Gets or sets a constant value to compare with the value entered by the user into the input control being validated. |
The following example compares two text boxes against each other. You can just as easily test to see whether a single box matches a specific set of criteria, as well.
<%@ page language="vb" runat="server"%> <script runat=server> sub Page_Load(sender as Object, e as EventArgs) if (IsPostBack) then Validate() end if end sub </script> <html> <head> <title>Validators - Compare</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h3>Set Up User Account</h3> Username: <asp:TextBox runat="server" /><br> Password: <asp:TextBox TextMode = "Password" runat="server" /><br> Confirm: <asp:TextBox TextMode = "Password" runat="server" /><br> <asp:CompareValidator ControlToValidate="PasswordConfirm" ControlToCompare="Password" ErrorMessage="Hey, They don't Match" runat="server" /><br> <asp:Button runat="server" text="Submit" /><br> </form> </body> </html>
<%@ page language="cs" runat="server"%> <script runat=server> void Page_Load(Object sender, EventArgs e) { if (IsPostBack) { Validate(); } } </script> <html> <head> <title>Validators - Compare</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h3>Set Up User Account</h3> Username: <asp:TextBox runat="server" /><br> Password: <asp:TextBox TextMode = "Password" runat="server" /><br> Confirm: <asp:TextBox TextMode = "Password" runat="server" /><br> <asp:CompareValidator ControlToValidate="PasswordConfirm" ControlToCompare="Password" ErrorMessage="Hey, They don't Match" runat="server" /><br> <asp:Button runat="server" text="Submit" /><br> </form> </body> </html>
In Figure 8.3, the CompareValidator checks the contents of the two text boxes and throws an error. As I said before, you can also use the ValueToCompare property to compare the CompareValidator against a defined value.
The RegularExpressionValidator allows you to compare the value of an input control against a regular expression. This provides a way to verify different types of data input against predictable patterns.
Note |
The regular expression is a powerful tool that allows you to match character patterns in blocks of text. For instance, all e-mail addresses contain a specific pattern that can vary in many ways, depending on how the prefix is formatted or what domain extension it contains. Regular expressions give you a way to pattern-match this type of data so you can verify that the user has input an email address that matches that pattern. The RegularExpressionValidator is one place where you will use regular expressions, but there are also some objects particularly the RegEx object, in the System.Text.RegularExpression namespace that will allow you to use regular expressions in any coding situation. For instance, you might want to find, replace, or edit a particular pattern of data as you retrieve it from a database. |
The RegularExpressionValidator has a single additional property and no additional methods (see Table 8.7).
Property | Description |
---|---|
ValidationExpression | Gets or sets the regular expression that determines the pattern used to validate a field. |
Regular expressions can be quite a complex subject and are way beyond the scope of this book. I've included a couple of things so that you can take advantage of the RegularExpressionValidator as well as learn more about regular expressions.
First, I've included two URLs for pages in the .NET Framework SDK. The first link takes you to the root page on .NET regular expressions. This provides links to other pertinent information on regular expressions. The second URL is for one of the specific links in the first page. It is a page with links to all the specific elements of regular expressions in the .NET Framework.
ms-help://MS.NETFrameworkSDK/cpguidenf/html/cpconcomregularexpressions.htm
ms-help://MS.NETFrameworkSDK/cpgenref/html/cpconregularexpressionslanguageelements.htm
Table 8.8 includes some regular expressions that you will find yourself using often. It gives you a jump start on using the RegularExpressionValidator as a foundation to build on. Some very good libraries of regular expressions for the .NET Framework are also available on the web and I would encourage you to search the web for these resources. Note that the expressions in Table 8.8 are simple versions and aren't the only ways to pattern-match these types of data. After you investigate, you will see that there are a million ways to skin a cat with regular expressions.
Data Type | Regular Expression |
---|---|
Date xx/xx/xxxx | ^\d{1,2}\/\d{1,2}\/\d{4}$ |
Email Address | ^[\w\.=-]+@[\w\.-]+\.[a-z]{2,4}$ |
Phone Number (xxx)xxx-xxxx | ^(\d{10}| \d{3}-\d{3}-\d{4}| \(\d{3}\)\s*\d{3}-\d{4})$ |
Zip Code xxxxx or xxxxx-xxxx | (^\d{5}$)| (^\d{5}-\d{4}$) |
The following code examples validate both an email address and a phone number. Let's take a look.
<%@ page language="vb" runat="server"%> <script runat=server> sub Page_Load() if (IsPostBack) then Validate() end if end sub </script> <html> <head> <title>Validators - Regular Expression</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> Email Address:<br> <asp:TextBox runat="server" /> <asp:RegularExpressionValidator ControlToValidate="OurEmail" ValidationExpression="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|( ([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" ErrorMessage="Invalid Email Entry" runat="server" /><br> Phone Number:<br> <asp:TextBox runat="server" /> <asp:RegularExpressionValidator ControlToValidate="OurPhone" ValidationExpression="^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$" ErrorMessage="Invalid Phone Number" runat="server" /><br> <asp:Button runat="server" text="Submit" /><br> </form> </body> </html>
<%@ page language="c#" runat="server"%> <script runat=server> void Page_Load(Object sender, EventArgs e) { if (IsPostBack) { Validate(); } } </script> <html> <head> <title>Validators - Regular Expression</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> Email Address:<br> <asp:TextBox runat="server" /> <asp:RegularExpressionValidator ControlToValidate="OurEmail" ValidationExpression="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|( ([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" ErrorMessage="Invalid Email Entry" runat="server" /><br> Phone Number:<br> <asp:TextBox runat="server" /> <asp:RegularExpressionValidator ControlToValidate="OurPhone" ValidationExpression="^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$" ErrorMessage="Invalid Phone Number" runat="server" /><br> <asp:Button runat="server" text="Submit" /><br> </form> </body> </html>
You can see the results of this experiment in Figure 8.4. Regular expression and specifically the RegularExpressionValidator will come in quite handy when you need to control the patterns of data that a user is allowed to input.
The CustomValidator provides a method to validate input data when none of the other validators can do the job. It provides a way for you to define custom functions, both client-side and server-side, against which to validate data. It has a single property called ClientValidationFunction (see Table 8.9) and an event called ServerValidate, which you call with the OnServerValidate method. This method specifies what function to use for server-side validation.
Property | Description |
---|---|
ClientValidationFunction | Gets or sets the name of the custom client-side script function to be used for validation. |
In the following example I've included only a server-side validation example, but if you want both types of validation present to prevent unnecessary server-side processing, you can easily create a JavaScript function and place its name in the ClientValidationFunction property as well.
<%@ page language="vb" runat="server"%> <script runat=server> sub Page_Load(sender as Object, e as EventArgs) if (IsPostBack) then Validate() if (Page.IsValid) Then OurLabel.Text = "Wahooo!!! You entered a valid number<br>" end if end if end sub sub SSValidate(source as Object, value as ServerValidateEventArgs) value.IsValid =((CInt(OurTextBox.Text) mod 3 = 0) or (CInt(OurTextBox.Text) mod 5 = 0)) end sub </script> <html> <head> <title>Validators - CustomValidator</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h2>Please insert a multiple of 3 or 5 </h2> <asp:Label EnableViewState="false" runat="server" /> <asp:TextBox runat="server" /> <asp:CustomValidator ControlToValidate="OurTextBox" OnServerValidate="SSValidate" ErrorMessage="Entry must be a multiple of 3 or 5" runat="server" /><br> <asp:Button runat="server" text="Submit" /><br> </form> </body> </html>
<%@ page language="c#" runat="server"%> <script runat=server> void Page_Load(Object sender, EventArgs e) { if (IsPostBack) { Validate(); if (Page.IsValid){ OurLabel.Text = "Wahooo!!! You entered a valid number<br>"; } } } void SSValidate(Object source, ServerValidateEventArgs value) { value.IsValid = (Int32.Parse(OurTextBox.Text) % 3 == 0 || Int32.Parse(OurTextBox. Text) % 5 == 0); } </script> <html> <head> <title>Validators - CustomValidator</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h2>Please insert a multiple of 3 or 5 </h2> <asp:Label EnableViewState="false" runat="server" /> <asp:TextBox runat="server" /> <asp:CustomValidator ControlToValidate="OurTextBox" OnServerValidate="SSValidate" ErrorMessage="Entry must be a multiple of 3 or 5" runat="server" /><br> <asp:Button runat="server" text="Submit" /><br> </form> </body> </html>
As you can see in Figure 8.5, I have designated through the CustomValidator that a multiple of 3 or 5 must be entered into the text box and the SSValidate process determines whether the IsValid property is set to true or false.
There are many times where you don't want the validation error messages inline with your text boxes, but would like the errors grouped together somewhere on the page. You could do this by putting all of the validation controls in the same place on the page, but this makes programming a bit more difficult to organize. It's easier to have the validators near the controls they validate. There is also a neat little trick that you can pull off using a validator's text property to place a highlight next to the input control and have the error message appear in the summary.
The ValidationSummary has a few properties that can help you control exactly how it behaves with regard to both client-side and server-side validation (see Table 8.10).
Property | Description |
---|---|
DisplayMode | Gets or sets the display mode of the validation summary. The valid possibilities are BulletList, List, and SingleParagraph. BulletList is the default. |
EnableClientScript | Gets or sets a value indicating whether the ValidationSummary control updates itself using client-side script. |
ForeColor | Gets or sets the color of the ErrorMessage text. |
HeaderText | Gets or sets the text that appears in the header of the summary. |
ShowMessageBox | Gets or sets a value indicating whether the validation summary is displayed in a client-side message box. If the EnableClientScript is set to false, this property has no effect. |
ShowSummary | Gets or sets a value indicating whether the validation summary is displayed inline. |
The following code sample sets EnableClientScript and ShowMessageBox to true so that any possible client-side verification is performed and the user is presented with an alert box if he tries to submit the page and the input data still isn't valid.
<%@ page language="vb" runat="server"%> <script runat=server> sub Page_Load(sender as Object, e as EventARgs) if (IsPostBack) then Validate() if (IsValid) then response.redirect("thankyou.aspx") end if end if end sub </script> <html> <head> <title>Validators Summary</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h3>What's your name and how many widgets do you want?</h3> You can buy between 1 and 10 widgets.<br> <table> <tr><td colspan="2"> <asp:ValidationSummary HeaderText="The following errors were found:" DisplayMode="List" ShowMessageBox="true" runat="server" /> </td></tr> <tr><td>Name:</td> <td><asp:TextBox runat="server" /> <asp:RequiredFieldValidator ControlToValidate="Name" Text="*" ErrorMessage="Name is a required field" runat="server" /> </td></tr> <tr><td># of Widgets</td> <td><asp:TextBox runat="server" /> <asp:RequiredFieldValidator ControlToValidate="Widgets" Text="*" ErrorMessage="Widgets is a required field" runat="server" /> <asp:RangeValidator ControlToValidate="Widgets" Type="Integer" MinimumValue="1" MaximumValue="10" Text="*" ErrorMessage="# of Widgets must be between 1 and 10" runat="server"/></td> </tr> <tr> <td> </td> <td><asp:Button runat="server" text="Submit" /></td> </tr> </table> </form> </body> </html>
<%@ page language="c#" runat="server"%> <script runat=server> void Page_Load(Object sender, EventArgs e) { if (IsPostBack) { Validate(); if (IsValid) { Response.Redirect("thankyou.aspx"); } } } </script> <html> <head> <title>Validators Summary</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h3>What's your name and how many widgets do you want?</h3> You can buy between 1 and 10 widgets.<br> <table> <tr><td colspan="2"> <asp:ValidationSummary HeaderText="The following errors were found:" DisplayMode="List" ShowMessageBox="true" runat="server" /> </td></tr> <tr><td>Name:</td> <td><asp:TextBox runat="server" /> <asp:RequiredFieldValidator ControlToValidate="Name" Text="*" ErrorMessage="Name is a required field" runat="server" /> </td></tr> <tr><td># of Widgets</td> <td><asp:TextBox runat="server" /> <asp:RequiredFieldValidator ControlToValidate="Widgets" Text="*" ErrorMessage="Widgets is a required field" runat="server" /> <asp:RangeValidator ControlToValidate="Widgets" Type="Integer" MinimumValue="1" MaximumValue="10" Text="*" ErrorMessage="# of Widgets must be between 1 and 10" runat="server"/></td> </tr> <tr> <td> </td> <td><asp:Button runat="server" text="Submit" /></td> </tr> </table> </form> </body> </html>
As you can see in Figure 8.6, the user received errors for entering bad data and was presented with an alert box to make the problem even more apparent.
Top |