1. Home
  2. Computing & Technology
  3. Delphi Programming
Using Validators in Delphi ASP.NET applications
Introducing client-side and server-side data validation using Validation Controls: RequiredFieldValidator, RangeValidator and ValidationSummary
 Join the Discussion
"Post your views and comments to this chapter of the free Asp.Net Delphi Programming Course"
Discuss!
 Related Resources
• A Beginner's Guide to Asp.Net Programming for Delphi developers.TOC

Welcome to the seventeenth chapter of the FREE online programming course:
A Beginner's Guide to Asp.Net Programming for Delphi developers.
Introducing client-side and server-side data validation using Validation Controls: RequiredFieldValidator, RangeValidator and ValidationSummary.

In the Introduction to Web Server Controls chapter, we've divided ASP.NET Web Server controls into several categories.
We continue our exploration of the System.Web.UI.WebControls namespace by investigating a variety of web controls designed to provide client and server side data validation.

Throughout this chapter, you'll learn about the following:

  • Validating user input
  • Client-side validation (+ Cassini "fix")
  • Server-side validation
  • Using ASP.NET Validation controls: RequiredFieldValidator, CompareValidator, RangeValidator, RegularExpressionValidator, ValidationSummary
  • Disabling validation
  • Validating user input
    Validating user input is a common scenario in any type of application, and ASP.NET applications are no exception. Whenever a user fills out a form, you almost always want to perform some validity check on the data being entered.
    ASP.NET provides a series of Web Controls that aid in the process of validating data - Validation Controls.

    There are two different kinds of validation you can add to a Web Form: client-side validation and server-side validation.

    Client-side validation is performed using the client-side (JavaScript) scripting language before the page is submitted to the server. This approach can improve response time in the page (by reducing postbacks and server round-trips); error messages are displayed as soon as the user leaves the control containing the error. Client side validation relies on the browser support for scripts.
    Server-side validation is performed on the server, usually by code in even procedures. This approach requires a round trip. While server-side validation seems too much time consuming (due to round-trips to the server), client-side validation also has limited functionality - validation can only be performed against data and rules passed to the client (and therefore, for example, no checks related to data in a database are possible).

    This is where ASP.NET Validation Controls come in: they provide the best of two worlds by rendering client side scripts on the client while still enabling server-side validation.

    Using Validation controls
    ASP.NET Validation control in the Tool Palette There are 5 types of individual validation controls, located inside the "Web Controls" category on the Tool Palette:
    • RequiredFieldValidator - use it to ensure that a value has been entered into a control
    • CompareValidator - checks a value entered into a control with a predefined value or with the contents of another control
    • RangeValidator - use it to ensure that the data entered fails within a certain range of values.
    • RegularExpressionValidator - ensures data validity using a specific regular expression. You'll use it, in most cases, to ensure data matches required formats: telephone number, zip code, etc.
    • CustomValidator - use it to set your own client side validation function, when you have a special scenario where none of the above validation controls can handle the job.

    Let's build a simple data entry form using validators:

    RequiredFieldValidator
    A simple RequiredFieldValidator Delphi sample
    1. Create a new ASP.NET application and drop one Label (ID = Label1, Text = "Years of experience"), one TextBox (ID = TextBox1) control and one Button (ID = Button1) control on the Web Form (WebForm1)
    2. Drop a RequiredFieldValidator (ID = RequiredFieldValidator1) control on a form and set its ControlToValidate to "TextBox1"
    3. Set RequiredFieldValidator1's ErrorMessage property to "Value required"
    This is how the RequiredFieldValidator1 gets displayed in the aspx view at design-time:

     <asp:RequiredFieldValidator 
      id="RequiredFieldValidator1"
      runat="server"
      errormessage="Value required" 
      controltovalidate="TextBox1"
      display="Dynamic">
     </asp:RequiredFieldValidator>
    

    Validation controls operate on other Web Controls by setting their ControlToValidate property. Each validation control can be used to validate only one Web Control, however you can use any number validation controls to check validity of a single web control.
    Each validator inherits from a BaseValidator control and provides a common set of properties:

    • ControlToValidate - specifies the input control to validate
    • ErrorMessage - specifies the message to be displayed to the user if validation fails
    • Display - determines how the ErrorMessage string is displayed. Static (default) allocates the rendering space for the validator. Dynamic allocates the rendering space if needed. Static is equal to Dynamic when the controls are rendered in the flow layout. None prevents the error message to be displayed at all.
    • EnableClientScript - determines if the client-side script is generated to enable client side validation (if enabled by browser)
    Validators at run time At run time, if validation fails, the validation control will display the ErrorMessage - make sure you position the validation control adjacent to the input control it validates. If EnableClientScript is true (default) the validation takes place as soon as the input control being validated looses the input focus.

    If you run the web form, and try to submit it with an empty textbox, the post back will be canceled and the RequiredFieldValidator will be displayed with the ErrorMessage specified.

    WebUIValidation.js; Cassini problems
    If you take a look at the resulting HTML, you'll find a reference to the "WebUIValidation.js" JavaScript file ASP.NET uses to perform client-side validity checks. By default, the script file will be installed into your default root in the aspnet_client directory. If you are using Cassini to debug your ASP.NET application you might experience problems with validators, here's how to "fix" Cassini to find the WebUIValidation.js.

    If EnableClientScript is false, or the browser does not support scripting, the page will be submitted and validity checks will be performed server-side. The IsValid property of the Page object can then be used to check for data validity.

    procedure TWebForm1.Button1_Click(
      sender: System.Object; 
      e: System.EventArgs);
    begin
      if Page.IsValid then
      begin
        // code to handle valid data here
      end;
    end;
    

    Note: it is a good practice to always perform the server side "Page.IsValid" check even if you have set EnableClientScript to true. Page.IsValid will also guard you from malicious and malformed requests and will ensure validation when a user has disabled client-side scripts for any reason.

    CompareValidator
    Let's now put CompareValidator into action. Place a CompareValidator below the RequiredFieldValidator and set the next set of properties:

     <asp:CompareValidator 
       id="CompareValidator1" runat="server"
       errormessage="Bad input" 
       controltovalidate="TextBox1"
       type="Integer" 
       operator="GreaterThan" 
       valuetocompare="5">
     </asp:CompareValidator>
    

    You already know what ControlToValidate and ErrorMessage are used for. The Type property specifies the data type used for comparison. Since this example asks for a developer's years of experience, set the Type property to "Integer". The Operator property ensures that only integer numbers greater than 5 (defined using the ValueToCompare) are accepted.

    Run the web form, ..., clicking on the button will result in a post-back, only if an integer number greater than 5 was provided in the text box.

    Validation summary
    In a more complex scenarios where a dozen of data input controls need to be evaluated before posting data to the server, you'll find that using a single control to display all validity error messages is much more user friendly (and provides a more flexibile approach for a developer).
    The ValidationSummary control gives you additional control on where and how validity error messages are displayed to the user. What's best, ValidationSummary is automatically populated with the ErrorMessage text from every validation control on the Web Form that derives from BaseValidator.
    By setting the Display property of each validation control to None, when using ValidationSummary, you will ensure that "standard" ErrorMessages are suppressed.

    Let's see an example.
    Drop a ListBox (ID = ListBox1) control on a web form and equip it with a RequiredFieldValidator (ID = RequiredFieldValidator2, ControlToValidate = ListBox1). Add a few entries in the Items property of the ListBox. Make sure all validators have their Display property set to false. Of course, do not forget to drop a a ValidationSummary control.

    At design-time:

    ValidationSummary at design-time

    And, at run time (after a click on a button):

    ValidationSummary strikes back!

    Disabling Validation for ASP.NET Server Controls
    There are times when you need to enable moving away from the page or submitting the page content even if the user did not fill out all the validated fields correctly. For example, a "Cancel" button on a data entry form should enable posting back to the server without the validation taking place. Every ASP.NET Control has the CausesValidation property - set it to false to specify that a postback can occur without triggering a validation check.

    You can also disable a validation control, set its Enabled property to false - it does not get rendered to the page at all.

    Finally, if you want to enable validation, but only on the server, you can set the validation control's EnableClientScript property to false.

    To the next chapter: A Beginner's Guide to ASP.NET Programming for Delphi developers
    That's it for today.

    While we have not discussed RangeValidator, RegularExpressionValidator and CustomValidator, the ideas presented in the article should help you quickly put those validators in action.

    In the next chapter we'll discuss postback processing. Stay tuned!

    If you need any kind of help at this point, please post to the Delphi Programming Forum where all the questions are answered and beginners are treated as experts.

    A Beginner's Guide to ASP.NET Programming for Delphi developers: Next Chapter >>
    >> Understanding ViewState and Postback Processing in ASP.NET applications

    Explore Delphi Programming
    About.com Special Features

    Holiday Central

    What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

    Family Tech Center

    Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

    1. Home
    2. Computing & Technology
    3. Delphi Programming

    ©2009 About.com, a part of The New York Times Company.

    All rights reserved.