- Chapter 3: Performing Form Validation with Validation Controls
- Requiring Fields: The RequiredFieldValidator Control
- Validating Expressions: The RegularExpressionValidator Control
- Comparing Values: The CompareValidator Control
- Checking for a Range of Values: The RangeValidator Control
- Summarizing Errors: The ValidationSummary Control
- Performing Custom Validation: The CustomValidator Control
- Disabling Validation
- Summary
Performing Custom Validation: The CustomValidator Control
The Validation controls included with ASP.NET enable you to handle a wide range of validation tasks. However, you cannot perform certain types of validation with the included controls. To handle any type of validation that is not covered by the standard validation controls, you need to use the CustomValidator control. All the properties, methods, and events of this control are listed in Table 3.6.
Table 3.6 CustomValidator Properties, Methods, and Events
Properties |
Description |
ClientValidationFunction |
Specifies the name of a client-side validation function. |
ControlToValidate |
Specifies the ID of the control that you want to validate. |
Display |
Sets how the error message contained in the Text property is displayed. Possible values are Static, Dynamic, and None; the default value is Static. |
EnableClientScript |
Enables or disables client-side form validation. This property has the value True by default. |
Enabled |
Enables or disables both server and client-side validation. This property has the value True by default. |
ErrorMessage |
Specifies the error message that is displayed in the ValidationSummary control. This error message is displayed by the control when the Text property is not set. |
IsValid |
Has the value True when the validation check succeeds and False otherwise. |
Text |
Sets the error message displayed by the control. |
Methods |
Description |
OnServerValidate |
Raises the ServerValidate event. |
Validate |
Performs validation and updates the IsValid property. |
Events |
Description |
ServerValidate |
Represents the function for performing the server-side validation. |
You cannot use any of the included Validation controls, for example, with information that is stored in a database table. Typically, you want users to enter a unique username and/or e-mail address when completing a registration form. To determine whether a user has entered a unique username or e-mail address, you must perform a database lookup.
Using the CustomValidator control, you can write any subroutine for performing validation that you wish. The validation can be performed completely server-side. Alternatively, you can write a custom client-side validation function to use with the control. You can write the client-side script using either JavaScript or VBScript.
To create the server-side validation routine, you'll need to create a Visual Basic subroutine that looks like this:
Sub CustomValidator_ServerValidate( s As object, e As ServerValidateEventArgs ) End Sub
This subroutine accepts a special ServerValidateEventArgs parameter that has the following two properties:
IsValidWhen this property is assigned the value True, the control being validated passes the validation check.
ValueThe value of the control being validated.
WARNING
The custom validation subroutine is not called when the control being validated does not contain any data. The only control that you can use to check for an empty form field is the RequiredFieldValidator control.
For this example, create a custom validation subroutine that checks for the string ASP.NET Unleashed. If you enter text into a TextBox control and it does not contain the name of this book, it fails the validation test.
First, you need to create a server-side version of the validation subroutine:
Sub CustomValidator_ServerValidate( s As Object, e As ServerValidateEventArgs ) Dim strValue As String strValue = e.Value.ToUpper() If strValue.IndexOf( "ASP.NET UNLEASHED" ) > -1 Then e.IsValid = True Else e.IsValid = False End If End Sub
This subroutine checks whether the string ASP.NET Unleashed appears in the value of the control being validated. If it does, the value True is assigned to the IsValid property; otherwise, the value False is assigned.
You could just implement custom validation with the server-side validation subroutine, which is all you need to get the CustomValidator control to work. However, if you want to get really fancy, you could implement it in a client-side script as well.
Be fancy. This VBScript client-side script implements the validation subroutine:
<Script Language="VBScript"> Sub CustomValidator_ClientValidate( s, e ) Dim strValue strValue = UCase( e.Value ) If Instr( strValue, "ASP.NET UNLEASHED" ) > 0 Then e.IsValid = True Else e.IsValid = False End If End Sub </Script>
This subroutine performs exactly the same task as the previous server-side validation subroutine; however, it is written in VBScript rather than Visual Basic.
After you create your server-side and client-side subroutines, you can hook them up to your CustomValidator control by using the OnServerValidate and ClientValidationFunction properties.
The page in Listing 3.19 illustrates how you can use the custom validation subroutines you just built.
Listing 3.19 CustomValidator.aspx
<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs ) If IsValid Then Response.Redirect( "ThankYou.aspx" ) End If End Sub Sub CustomValidator_ServerValidate( s As Object, e As ServerValidateEventArgs ) Dim strValue As String strValue = e.Value.ToUpper() If strValue.IndexOf( "ASP.NET UNLEASHED" ) > -1 Then e.IsValid = True Else e.IsValid = False End If End Sub </script> <html> <head> <Script Language="VBScript"> Sub CustomValidator_ClientValidate( s, e ) Dim strValue strValue = UCase( e.Value ) If Instr( strValue, "ASP.NET UNLEASHED" ) > 0 Then e.IsValid = True Else e.IsValid = False End If End Sub </Script> <title>CustomValidator.aspx</title> </head> <body> <form Runat="Server"> Enter the name of your favorite book: <br> <asp:CustomValidator ControlToValidate="txtFavBook" ClientValidationFunction="CustomValidator_ClientValidate" OnServerValidate="CustomValidator_ServerValidate" Display="Dynamic" Text="You must type ASP.NET Unleashed!" Runat="Server" /> <br> <asp:TextBox ID="txtFavBook" TextMode="Multiline" Columns="50" Rows="3" Runat="Server" /> <p> <asp:Button Text="Submit!" OnClick="Button_Click" Runat="Server" /> </form> </body> </html>
Validating Credit Card Numbers
In this section, you look at a slightly more complicated but more realistic application of the CustomValidator control. You learn how to write a custom validation function that checks whether a credit card number is valid.
The function uses the Luhn algorithm xto check whether a credit card is valid. This function does not check whether credit is available in a person's credit card account. However, it does check whether a string of credit card numbers satisfies the Luhn algorithm, an algorithm that the numbers in all valid credit cards must satisfy.
The page in Listing 3.20 contains a TextBox control that is validated by a CustomValidator. If you enter an invalid credit card number, the validation check fails and an error message is displayed.
NOTE
You can test the form contained in Listing 3.20 by entering your personal credit card number or by entering the number 8 repeated 16 times.
Listing 3.20 CustomValidatorLuhn.aspx
<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs) If IsValid Then Response.Redirect( "Thankyou.aspx" ) End If End Sub Sub ValidateCCNumber( s As Object, e As ServerValidateEventArgs ) Dim intCounter As Integer Dim strCCNumber As String Dim blnIsEven As Boolean = False Dim strDigits As String = "" Dim intCheckSum As Integer = 0 ' Strip away everything except numerals For intCounter = 1 To Len( e.Value ) If IsNumeric( MID( e.Value, intCounter, 1 ) ) THEN strCCNumber = strCCNumber & MID( e.Value, intCounter, 1 ) End If Next ' If nothing left, then fail If Len( strCCNumber ) = 0 Then e.IsValid = False Else ' Double every other digit For intCounter = Len( strCCNumber ) To 1 Step -1 If blnIsEven Then strDigits = strDigits & cINT( MID( strCCNumber, intCounter, 1 ) ) * 2 Else strDigits = strDigits & cINT( MID( strCCNumber, intCounter, 1 ) ) End If blnIsEven = ( NOT blnIsEven ) Next ' Calculate CheckSum For intCounter = 1 To Len( strDigits ) intCheckSum = intCheckSum + cINT( MID( strDigits, intCounter, 1 ) ) Next ' Assign results e.IsValid = (( intCheckSum Mod 10 ) = 0 ) End If End Sub </script> <html> <head><title>CustomValidatorLuhn.aspx</title></head> <body> <form Runat="Server"> Enter your credit card number: <br> <asp:TextBox ID="txtCCNumber" Columns="20" MaxLength="20" Runat="Server" /> <asp:CustomValidator ControlToValidate="txtCCNumber" OnServerValidate="ValidateCCNumber" Display="Dynamic" Text="Invalid Credit Card Number!" Runat="Server" /> <p> <asp:Button Text="Submit!" OnClick="Button_Click" Runat="Server" /> </form> </body> </html>