6.2 Validation Control Architecture


Validation controls provide a simple, yet flexible way of validating form data on both the client and the server. To use a validation control, you add it to your form where you would like an error indicator to be displayed, typically adjacent to the field it is validating. You then associate it with another control on the page to validate, and when the user interacts with the form, the validation control enforces its validation on the control, both on the client, using client-side JavaScript, and the server, all with just one control. As an example, Listing 6-2 shows the use of a RequiredFieldValidator control to validate that a field contains a value. In this case, we are validating that the TextBox with an ID equal to _name is not left blank.

Listing 6-2 Adding a RequiredFieldValidator Control to a Form
 <asp:TextBox id="_name" runat=server/> <asp:RequiredFieldValidator      ControlToValidate="_name"      Display="Static"      InitialValue=""      runat=server      ErrorMessage="The name field must be completed."> *** </asp:RequiredFieldValidator> 

Note that the ControlToValidate property of the validation control associates it with the TextBox with the identifier _name in this case. The ErrorMessage property contains the string that is used in the summary of errors for a page. We will see how this is used when we discuss the ValidationSummary control. Finally, the HTML that you place within the validation control (in our case, just the text character "*") is what is displayed when the validation fails. It is your job to place the validation control at the location where this error HTML should appear ”very often this will be in a table cell adjacent to the input control it is validating. If you neglect to place any HTML in the body of the validation control, it will display the ErrorMessage string both at the location of the control and in the ValidationSummary control, if there is one.

The Display property of a validation control indicates whether the value of this control should occupy space when it is not being shown. If this is set to static , the validation control renders as a span element whose visibility style attribute is toggled between hidden and visible . If it is set to dynamic , the control renders as a span element whose display style is toggled between none and inline . The difference between these two is that setting it to dynamic causes the span element to not occupy space on the form when it is not visible. You may want to specify dynamic if you have more than one validation control associated with a field, only one of which will ever display a message at a time (such as validating that a field is not empty and that it has a correctly formatted telephone number). You could also specify none for the Display property if the control never displayed any HTML error message (perhaps it displays only errors in the summary of errors for a page). Figure 6-2 shows the two renderings of a RequiredFieldValidator control with different Display attribute values.

Figure 6-2. Validation Control Rendering

graphics/06fig02.gif

6.2.1 Page Validation

Adding a validation control to a form enables both client-side (for browsers that support it) and server-side validation. Server-side validation occurs once a page has been loaded and all the controls on the page have had their values restored. The Page class maintains a list of all the validation controls defined on that page in its Validators collection. Each validation control implements the IValidator interface, shown in Listing 6-3. This interface defines two properties, ErrorMessage and IsValid , and a method called Validate() .

Listing 6-3 The IValidator Interface
 public interface IValidator {   string ErrorMessage {get; set;}   bool IsValid {get; set;}   void Validate(); } 

Invoking the Validate() method on a validation control requests the control to execute its validation algorithm. The Page class also exposes a top-level Validate() method that can be used to collectively invoke all Validate() methods on all validation controls on that page. Similarly, the Page class exposes a Boolean property, IsValid , indicating whether or not all the validation controls succeeded their validation on that page. Figure 6-3 shows this validation control architecture.

Figure 6-3. Validation Control Architecture

graphics/06fig03.gif

As soon as you place a validation control on a page, it is imperative that you check the IsValid flag of the Page class before using any of the data posted by the client. It is a common misconception that if validation fails on a page, the code for that page will not execute. On the contrary, the only thing that happens when server-side validation fails is that the IsValid flag of the Page class is set to false , and each validation control that failed renders itself as a visible span so that the error indicator shows up when the page is redisplayed to the user.

It is also important to realize exactly when server-side validation occurs. The IsValid flag will be set properly after the validation controls have had their Validate() routines invoked, which will happen implicitly in the Page class immediately after the Load event fires. This means that if you are looking at data submitted by the user in a handler for the Load event, there is no way for you to know whether it is valid yet or not. Instead, you should work with client-submitted data in server-side event handlers such as the Click event of a Button , at which point the Page will have performed validation, and you can safely check the IsValid property. If you truly need to access client-submitted data in your Load handler, you can always explicitly invoke the Validate() method of your Page class. Figure 6-4 shows the complete post-back sequence and where validation occurs in that sequence.

Figure 6-4. Server-Side Validation During Post-Back

graphics/06fig04.gif

6.2.2 Client-Side Validation

If you try accessing a page with validation controls, you will notice that it performs validation within the browser and does not even submit the page until all the validated fields have acceptable data. ASP.NET performs client-side validation implicitly when you add validation controls to a page, as long as the client browser supports it.

As part of the HTML rendering of a Page with validation controls, ASP.NET generates a script reference to the file WebUIValidation.js , which contains a collection of validation routines. It also generates embedded client-side JavaScript in the rendered HTML page that interacts with the imported validation routines. Figure 6-5 shows the interaction of the various script elements involved with client-side validation.

Figure 6-5. Script Elements of Client-Side Validation

graphics/06fig05.gif

One of the JavaScript elements that the Page class generates when it contains validation controls is a global array named Page_Validators . This array is initialized to contain references to all the span elements rendered by validation controls. Similarly, another global array, named Page_ValidationSummaries , contains all the ValidationSummary controls (usually just one) for that page. All the routines in the WebUIValidation.js file depend on these two arrays being populated when the page loads. The other thing a Page does when it renders with validation controls is to add an explicit call to Page_ClientValidate() in any controls that perform post-backs (typically buttons ). Finally, an explicit call to ValidatorOnLoad() is injected into the rendered page that is called when the page loads.

In the implementation of ValidatorOnLoad() , each of the span elements in the Page_Validators array is accessed, and the ControlToValidate attribute is extracted. This control is then passed into a function called ValidatorHookupControl , in which its onchange event is wired up to the ValidatorOnChange() function. Now the actual validation can happen at one of two times. First, it always happens when the user explicitly posts the page back. When the entire page is submitted, the Page_ClientValidate() routine is called, which iterates across all the validators, invoking their corresponding evaluation functions, and if any one of them fails, the submission of the form is aborted and the validation error messages are displayed. The other time validation can happen is when a control that has an associated validator loses focus and fires its OnChange event. This fires only the validator associated with that control. There is also logic in place to avoid enforcing RequiredFieldValidator controls until the page has been submitted (or has attempted to be submitted) at least once. This allows users to fill in fields in any order without being warned that a field is required.



Essential ASP.NET With Examples in C#
Essential ASP.NET With Examples in C#
ISBN: 0201760401
EAN: 2147483647
Year: 2003
Pages: 94
Authors: Fritz Onion

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