Using the CustomValidator Control


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.

Listing 3.14. ShowCustomValidator.aspx

[View full width]

<%@ 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  runat="server">     <title>Show CustomValidator</title> </head> <body>     <form  runat="server">     <div>     <asp:Label                  Text="Comments:"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  TextMode="MultiLine"         Columns="30"         Rows="5"         Runat="server" />     <asp:CustomValidator                  ControlToValidate="txtComments"         Text="(Comments must be less than 10 characters)"         OnServerValidate="valComments_ServerValidate"         Runat="server" />     <br /><br />     <asp:Button                  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.

Warning

If you don't associate a client validation function with a CustomValidator control, then the CustomValidator doesn't render an error message until you post the page back to the server. Because the other validation controls prevent a page from being posted if the page contains any validation errors, you won't see the error message rendered by the CustomValidator control until you pass every other validation check in a page.


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.

Listing 3.15. ShowCustomValidatorJS.aspx

[View full width]

<%@ 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  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  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  runat="server">     <div>     <asp:Label                  Text="Comments:"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  TextMode="MultiLine"         Columns="30"         Rows="5"         Runat="server" />     <asp:CustomValidator                  ControlToValidate="txtComments"         Text="(Comments must be less than 10 characters)"         OnServerValidate="valComments_ServerValidate"         ClientValidationFunction="valComments_ClientValidate"         Runat="server" />     <br /><br />     <asp:Button                  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.

Listing 3.16. ShowValidateEmptyText.aspx

[View full width]

<%@ 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  runat="server">     <title>Show Validate Empty Text</title> </head> <body>     <form  runat="server">     <div>     <asp:Label                  Text="Product Code:"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Runat="server" />     <asp:CustomValidator                  ControlToValidate="txtProductCode"         Text="(Invalid product code)"         ValidateEmptyText="true"         OnServerValidate="valProductCode_ServerValidate"         Runat="server" />     <br /><br />     <asp:Button                  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.


Listing 3.17. TimedTest.aspx

[View full width]

<%@ 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  runat="server">     <title>Timed Test</title> </head> <body>     <form  runat="server">     <div>     <p>     You have 5 seconds to answer the following question:     </p>     <asp:Label                  Text="What was Aristotle's first name?"         AssociatedControl         Runat="server" />         <br />     <asp:TextBox                  Runat="server" />     <asp:CustomValidator                  Text="(You answered too slowly!)"         OnServerValidate="valAnswer_ServerValidate"         Runat="server"  />     <br /><br />     <asp:Button                  Text="Submit"         Runat="server" />     <asp:Button                  Text="Try Again!"         CausesValidation="false"         OnClick="btnAgain_Click"         Runat="server" />     </div>     </form> </body> </html> 




ASP. NET 2.0 Unleashed
ASP.NET 2.0 Unleashed
ISBN: 0672328232
EAN: 2147483647
Year: 2006
Pages: 276

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