- Overview of the Validation Controls
- Using the RequiredFieldValidator Control
- Using the RangeValidator Control
- Using the CompareValidator Control
- Using the RegularExpressionValidator Control
- Using the CustomValidator Control
- Using the ValidationSummary Control
- Creating Custom Validation Controls
- Summary
Using the CustomValidator Control
If none of the other validation controls perform the type of validation that you need, you can always use the CustomValidator control. You can associate a custom validation function with the CustomValidator control.
The CustomValidator control has three important properties:
- ControlToValidate— The ID of the form field being validated.
- Text— The error message displayed when validation fails.
- ClientValidationFunction— The name of a client-side function used to perform client-side validation.
The CustomValidator also supports one event:
- ServerValidate— This event is raised when the CustomValidator performs validation.
You associate your custom validation function with the CustomValidator control by handling the ServerValidate event.
For example, imagine that you want to validate the length of a string entered into a form field. You want to ensure that a user does not enter more than 10 characters into a multi-line TextBox control. The page in Listing 3.14 contains an event handler for a CustomValidator control's ServerValidate event, which checks the string's length.
Example 3.14. ShowCustomValidator.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Protected Sub valComments_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) If args.Value.Length > 10 Then args.IsValid = False Else args.IsValid = True End If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show CustomValidator</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblComments" Text="Comments:" AssociatedControlID="txtComments" Runat="server" /> <br /> <asp:TextBox id="txtComments" TextMode="MultiLine" Columns="30" Rows="5" Runat="server" /> <asp:CustomValidator id="valComments" ControlToValidate="txtComments" Text="(Comments must be less than 10 characters)" OnServerValidate="valComments_ServerValidate" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" /> </div> </form> </body> </html>
The second parameter passed to the ServerValidate event handler is an instance of the ServerValidateEventArgs class. This class has two properties:
- Value— Represents the value of the form field being validated.
- IsValid— Represents whether validation fails or succeeds.
- ValidateEmptyText— Represents whether validation is performed when the form field being validated does not contain a value.
In Listing 3.14, if the string represented by the Value property is longer than 10 characters, then the value False is assigned to the IsValid property and validation fails. Otherwise, the value True is assigned to the IsValid property and the input field passes the validation check (see Figure 3.12).
Figure 3.12 Validating field length with the CustomValidator control.
The ServerValidate event handler in Listing 3.14 is a server-side function. Therefore, validation does not occur until the page is posted back to the web server. If you want to perform validation on both the client (browser) and server, then you need to supply a client-side validation function.
The page in Listing 3.15 illustrates how you can associate a client-side validation function with the CustomValidator control. This page also checks the length of the string entered into a TextBox control. However, it checks the length on both the browser and server.
Example 3.15. ShowCustomValidatorJS.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Protected Sub valComments_ServerValidate(ByVal source As Object, ByVal args AsServerValidateEventArgs) If args.Value.Length > 10 Then args.IsValid = False Else args.IsValid = True End If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <script type="text/javascript"> function valComments_ClientValidate(source, args) { if (args.Value.length > 10) args.IsValid = false; else args.IsValid = true; } </script> <title>Show CustomValidator with JavaScript</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblComments" Text="Comments:" AssociatedControlID="txtComments" Runat="server" /> <br /> <asp:TextBox id="txtComments" TextMode="MultiLine" Columns="30" Rows="5" Runat="server" /> <asp:CustomValidator id="valComments" ControlToValidate="txtComments" Text="(Comments must be less than 10 characters)" OnServerValidate="valComments_ServerValidate" ClientValidationFunction="valComments_ClientValidate" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" /> </div> </form> </body> </html>
Notice that the CustomValidator control in Listing 3.15 includes a ClientValidationFunction property. This property contains the name of a JavaScript function defined in the page's <head> tag.
The JavaScript validation function accepts the same two parameters as the server-side validation function. The first parameter represents the CustomValidator control, and the second parameter represents an object that includes both a Value and an IsValid property. The client-side function is nearly identical to the server-side function (with the important difference that it is written in JavaScript).
Unlike the RangeValidator, CompareValidator, and RegularExpressionValidator controls, you can validate a form field with the CustomValidator control even when the form field is left blank. The CustomValidator control includes a property named the ValidateEmptyText property. You can use this property to cause the CustomValidator control to validate a form field even when the user hasn't entered a value into the form field. For example, the page in Listing 3.16 contains a TextBox that requires a product code that contains exactly four characters.
Example 3.16. ShowValidateEmptyText.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub valProductCode_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs) If args.Value.Length = 4 Then args.IsValid = True Else args.IsValid = False End If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show Validate Empty Text</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblProductCode" Text="Product Code:" AssociatedControlID="txtProductCode" Runat="server" /> <br /> <asp:TextBox id="txtProductCode" Runat="server" /> <asp:CustomValidator id="valProductCode" ControlToValidate="txtProductCode" Text="(Invalid product code)" ValidateEmptyText="true" OnServerValidate="valProductCode_ServerValidate" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" /> </div> </form> </body> </html>
Notice that the CustomValidator control in Listing 3.16 includes a ValidateEmptyText property which has the value True. If the ValidateEmptyText property was not included, and you submitted the form without entering any data, then no validation error would be displayed.
Finally, unlike the other validation controls, you are not required to associate the CustomValidator control with any form field. In other words, you don't need to include a ControlToValidate property.
For example, the page in Listing 3.17 contains a timed test. If you don't answer the question within five seconds, then the CustomValidator control displays a validation error message (see Figure 3.13).
Figure 3.13 Performing validation against no particular field.
Example 3.17. TimedTest.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub Page_Load() If Not Page.IsPostBack Then ResetStartTime() End If End Sub Protected Sub btnAgain_Click(ByVal sender As Object, ByVal e As System.EventArgs) ResetStartTime() End Sub Sub ResetStartTime() Session("StartTime") = DateTime.Now End Sub Protected Sub valAnswer_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Dim startTime As DateTime = CType(Session("StartTime"), DateTime) If startTime.AddSeconds(5) > DateTime.Now Then args.IsValid = True Else args.IsValid = False End If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Timed Test</title> </head> <body> <form id="form1" runat="server"> <div> <p> You have 5 seconds to answer the following question: </p> <asp:Label id="lblQuestion" Text="What was Aristotle's first name?" AssociatedControlID="txtAnswer" Runat="server" /> <br /> <asp:TextBox id="txtAnswer" Runat="server" /> <asp:CustomValidator id="valAnswer" Text="(You answered too slowly!)" OnServerValidate="valAnswer_ServerValidate" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" /> <asp:Button id="btnAgain" Text="Try Again!" CausesValidation="false" OnClick="btnAgain_Click" Runat="server" /> </div> </form> </body> </html>