![]() |
< Day Day Up > |
![]() |
16.4. Validation ControlsOne of the more frustrating Internet experiences is to fill in a long form, submit it, and梐fter a lengthy wait梙ave it rejected due to an invalid field entry. Any well-designed form should attempt to avoid this by including client-side verification to check fields before the form is submitted. Validation is typically used to ensure that a field is not empty, that a field contains a numeric value only, that a phone number or credit card has the correct format, and that an e-mail address contains the @ character. JavaScript is traditionally used for this purpose. ASP.NET offers validation controls as a flexible alternative to implementing your own client-side JavaScript functions. The purpose of these controls is to perform a specific type of validation on an associated control. For example, a RequiredFieldValidator control checks an input control to ensure it is not empty. Table 16-5 lists the six built-in validation controls along with their unique properties and values.
Only the final control in the table, ValidationSummary, does not perform a validation. Instead, it displays a summary of the errors generated by the other validation controls. Using Validation ControlsValidation controls are used only with controls that have a single input field type. These include the HTMLInputText, HTMLSelect, TextBox, DropDownList, and ListBox controls. ASP.NET implements the validation function on both the server and client side. To handle the client side, it includes a .js file containing validation code in the response to the browser. Note, however, that if scripting is disabled on the browser, only client-side checking will occur. To illustrate the mechanics of using a validation control, here is the code to associate a RequiredFieldValidator and RangeValidator control with a TextBox control. The range validator control uses its MaximumValue and MinimumValue properties to ensure that the value entered in the text box is a numeric value from 0 to 12. <td><asp:TextBox Width=30 id=hti maxlength=2 runat=server></td> <asp:RequiredFieldValidator runat=server ControlToValidate="hti" ErrorMessage="Must enter height value." Display="dynamic"> </asp:RequiredFieldValidator> <asp:RangeValidator ControlToValidate="hti" MaximumValue="12" MinimumValue="0" Type="Integer" Display="dynamic " ForeColor="Blue" ErrorMessage="Invalid Height." runat=server> </asp:RangeValidator> This example also illustrates useful properties that all validator controls inherit from the BaseValidator class:
Of the controls listed in Table 16-4, the CustomValidator and ValidationSummary exhibit unique behavior that requires further explanation. CustomValidator ControlThere are many common validation patterns that the built-in validation controls do not handle. For example, the contents of one control may be dependent on another, such as when a credit card number format depends on the type of card selected. Another common example is to require that a string entered in a field conform to a minimum and maximum length. Cases such as these are handled with a CustomValidator control that points to server-side and/or client-side routines that implement custom validation logic. To demonstrate how this control works, let's use it to validate a field that accepts a password, which must be between 8 and 12 characters in length. The declaration of the control is similar to that of the other validation controls. The main difference is the ClientValidationFunction and OnServerValidate fields that specify client and server routines to validate the associated password field. <input type=password runat="server" /> <br> <asp:CustomValidator ControlToValidate="pw" ClientValidationFunction="checkPWClient" OnServerValidate="checkPW" Display=dynamic ErrorMessage="A password must be between 8 and 12 characters." runat="server"/> The validation routines contain identical logic. The client side is written in JavaScript and the server side in C#. They are contained in separate <script/> blocks in the .aspx file. <script language=javascript> <!? // Client side function to check field length function checkPWClient(source, args) { var pw = args.Value; var ln= pw.length; args.IsValid=true; if(ln <8 || ln > 12) args.IsValid=false } //--> </script> <script Language="C#" runat="Server"> private void checkPW(object source, ServerValidateEventArgs args){ if(args.Value.Length<8 || args.Value.Length>12) {args.IsValid=false; } else{ args.IsValid=true; } } </script> Two parameters are passed to the validation routines: source and args. Args is the more important of the two. Its value property exposes the content of the form field being validated. In this example, the length of the field value is checked. If it falls within the bounds, IsValid is set to true; otherwise, it is set to false. A false value triggers the error message defined by the CustomValidator control. For consistency with the built-in validation controls, include both server- and client-side routines for custom validation. If only one is to be implemented, server side is always preferred. ValidationSummary ControlThis control collects all of the error messages generated by the validation controls and displays them as a list or customizable paragraph. The messages are displayed either within the control (as a <span> element within the HTML) or as a pop-up window by setting the ShowMessageBox to true.
<asp:ValidationSummary id=validsumm runat="server"
ShowMessageBox=true
DisplayMode=List
ShowSummary=false>
</asp:ValidationSummary>
The most important factor to consider when deciding how to display validation error messages is that the ValidationSummary control displays messages when a form is submitted, and individual validation controls display a message when their associated control loses focus. Thus, displaying the message at a validation control provides immediate feedback to the user. Also note that if the validation control has its Display property set to static or dynamic, the error message is displayed by both the validation control and the ValidationSummary control. |
![]() |
< Day Day Up > |
![]() |