16.4. Validation Controls

 < Day Day Up > 

One of the more frustrating Internet experiences is to fill in a long form, submit it, and after a lengthy wait have 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.

Table 16-5. Validation Controls

Control

Properties

Description and Possible Values

 RequiredField Validator 

Checks whether input control field contains a value.

CompareValidator

Compares the value of an input control with a constant or other control.

Operator

Has value of:

Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, DataTypeCheck

Type

Currency, Date, Double, Integer, String.

ValueToCompare

Constant value used for comparison.

ControlToCompare

Other control to compare value with.

RangeValidator

Checks the value of the input control against a range of values.

MaximumValue

Constant value that represents upper value.

MinimumValue

Constant value that represents lowest value.

Type

Currency, Date, Double, Integer, String.

 RegularExpression Validator 

Matches the value of the input control against a regular expression.

ValidationExpression

Regex to match input control's value against.

CustomValidator

Checks a field's value against custom validation logic.

ClientValidationFunction

JavaScript client-side function to perform validation.

OnServerValidate

Server-side method to perform validation.

ValidationSummary

Collects and lists all the error messages from the form validation process.

DisplayMode

Format of error messages:

BulletList, List, SingleParagraph

HeaderText

Title for error message summary.

ShowMessageBox

Display errors in pop-up box: true or false.

ShowSummary

Display errors on control: TRue or false.


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 Controls

Validation 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:

  • ControlToValidate. Set to the identifier of the control to be validated.

  • Display. static, dynamic, or none. This specifies how the error message takes up space on the form: static reserves space and makes the message visible when it is needed; dynamic uses no space on the form until it is displayed; none is used when the error message is to be displayed by the ValidationSummary control.

  • ForeColor. Sets the color of the error message text. Red is the default.

  • ErrorMessage. The message displayed when a validation exception is detected.

  • ValidationGroup. A string value that enables validation controls to be grouped by assigning the same value to this property. When a Button control that has its ValidationGroup property set to a group value submits a form, only controls with validators in the group are validated. This allows sections of a page to be validated separately. This property is introduced in ASP.NET 2.0.

Of the controls listed in Table 16-4, the CustomValidator and ValidationSummary exhibit unique behavior that requires further explanation.

CustomValidator Control

There 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 Control

This 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 > 


    Core C# and  .NET
    Core C# and .NET
    ISBN: 131472275
    EAN: N/A
    Year: 2005
    Pages: 219

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