In-depth explanation of asp+ verification (transfer from Ms one)

Source: Internet
Author: User
Tags foreach config implement object model relative valid versions root directory
asp+ in-depth explanation asp+ validation
Anthony Moore
Microsoft Corporation
October 2000

Summary: For a detailed explanation of using asp+ to validate Web controls.

Directory


Brief introduction
Entry
When did something happen?
Server-side validation sequence
Client-side validation
Validation rules and useful error messages
Functions of Enabled, Visible and Display properties
CustomValidator control
Which controls can be validated?
End


--------------------------------------------------------------------------------


Brief introduction

This article explains in detail how the asp+ validation controls work. If you want to build a complex page that contains validation controls, or you want to extend the validation framework, it is recommended that you read this article. If you want to learn to use a validation control, or if you want to decide whether to use a validation control, see "User input Validation in asp+".


Entry

We know that it is important to understand validation throughout the asp+ development process. Looking at most of today's commercial Web sites, you'll find that there are many forms in these sites that are obviously performing validation by executing a lot of handwritten code. Writing validation code is not an interesting task. It might be tempting to write code to display a datasheet or dynamically generate a chart, but no one can prove to his colleagues that this "cool" method prevents the entry of NULL values in the last Name field.

For some other reason, the validation of WEB applications is also cumbersome. HTML 3.2 has a lot of restrictions on what you can control or feedback you can get from the user, so it's not possible to apply techniques that you can use on a more full-featured client, such as prohibiting users from entering certain characters or beeping. Using browser scripts can result in more robust validation. However, this method is difficult to prove, because the client browser does not necessarily have script, and malicious users can bypass. Therefore, in order to ensure site security, it is necessary to the server to do the same check.

When developing asp+, our intention was to use only one control to handle validation, which might have been a TextBox control that could display errors. However, when the control was designed, it was found that the desire could not be achieved. We studied a large number of data entry forms and tried to find a solution that could be applied to as many forms as possible. We find that data entry forms have many interesting features:

Although error messages or icons are often adjacent to input elements, they are almost always in different cells of the table.
There is often a region in the page that summarizes all errors.
Many sites contain client-side scripting to provide faster feedback, while preventing a round-trip to and from the server.
Many sites that contain client script display a message box when an error occurs.
Not only will the text input be validated, but the Drop-down list and radio buttons will also be validated.
If a field is empty, the site usually displays information or icons that are different when the entry is not valid.
Many validation checks can be a good substitute for commonly used expressions.
Validation is typically based on a comparison between two inputs.
More than 90% or 90% of the validation tasks are common operations, such as checking names or postal codes. Most sites still seem to be doing this repeatedly.
Because the differences between sites are usually too large to get a perfect solution to handle all the validation tasks for each site.
Given all of the above, the resulting solution includes five validator controls, ValidationSummary controls, and integration with the Page object. It is also obvious that the solution needs to be extended, with an API on both the client and server.

We looked at the various validations we were conducting and found that we seemed to need a larger toolbox. In most component environments, such as microsoft®activex®, we might have tried to integrate the functionality of all validation controls into one control, dealing with different properties in different modes. Fortunately, however, there is a magical inheritance in the Microsoft®.net framework that provides a set of controls for specific validation of specific properties because the extra work required to derive each new control is very small.

Most of the work done by these controls is implemented in their common parent basevalidator. You can also derive from BaseValidator or other controls to complete the work. In fact, even though BaseValidator is lazy to implement its own Text property, it inherits from the Label property.


When did something happen?

Understanding the sequence of events is very effective when working with pages that contain validation Web controls. If an authentication condition is optional, you need to know exactly when to authenticate on the client and on the server. If you want to write your own validation routines, it can be time-consuming or has side effects. Also, it is important to understand the timing of invoking validation routines.

First, let's take a look at the server.


Server-side validation sequence

It is important to understand the validity of a page. If you are accustomed to working with forms in Visual Basic or similar full-featured client tools, you need to spend a certain amount of time understanding them. All the objects on the page and on the page are not always valid when interacting with the user, although this is sometimes the case on the surface.

The following is a simplified sequence of events for the first time a page is accessed:

Creates a page and its controls based on an ASPX file.
Triggers the Page_Load event.
Page and control properties are saved in a hidden field.
Pages and controls into HTML.
Discard all content.
Now, when a user clicks a button or a similar control, it returns to the server and executes a similar sequence of events. The sequence is called the return sequence:

Creates a page and its controls based on an ASPX file.
Restores page and control properties from hidden fields.
Updates the page control based on user input.
Triggers the Page_Load event.
Triggers a change notification event.
Page and control properties are saved in a hidden field.
Pages and controls into HTML.
Discard all content again.
Why don't we keep all the objects in memory? Because a Web site built using asp+ cannot handle a very large number of users. As a result, the server's memory retains only what is immediately to be processed.

When will server-side validation be performed? The first time the page information is fetched, server-side validation is not done at all. Most end users are very serious and we allow users to confirm that the information they fill out on the form is correct, and then we use the red text to notify the user of the wrong information.

In the return sequence of events, validation occurs between steps 3rd and 4th. That is, validation is done after the data from the user is loaded back into the control's properties, but before most code executes. This means that when you write user event code, you can usually take advantage of the validation that you have already made. In general, you will want to do this.

The disadvantage of validating at this point is that it is too late if you want to programmatically modify some of the properties that affect the validation. For example, you may find that if you write code to enable or disable a validation control or change the properties of a validation control, you will not see any impact until the page is processed the next time. This problem can be avoided by using the following two methods:

Modify the properties before making the validation.
Re-validate the control after the property has changed.
Both of these methods need to use validation properties and methods that are valid on the Page object.

Page API

The Page object contains some important properties and methods related to server-side validation. The properties and methods are summarized in table 1:

Table 1. Properties and methods of the Page object

Description of property or method
IsValid Property This is the most useful property. This property can check whether the entire form is valid. This check is typically done before the database is updated. This property is true only if all objects in the validators set are valid, and the value is not cached.
Validators property The collection of all validation objects for this page. This is a collection of objects that implement the IValidator interface.
A method that is invoked when the Validate method is validated. The default way to perform on the Page object is to go to each validator and ask the validators to evaluate themselves.


Validators collections are useful for many tasks. The collection is a collection of objects that implement the IValidator interface. I use the Word object instead of the control because the Page object focuses on the IValidator interface. Since all validators are usually the visual controls that are used to implement IValidator, anyone should be able to use any of the validation objects and add the validation object to the page.

The IValidator interface contains the following properties and methods:

Table 2. Properties and methods of IValidator interface

Description of property or method
The IsValid property indicates whether the validation checks performed by a separate validation object have passed. You can change the value manually after validation.
The ErrorMessage property describes the errors that validation objects will verify and the errors that may be displayed to the user.
The Validate method performs a validation check on the validation object to update its IsValid value.


You can use this interface to perform some interesting tasks. For example, to reset a page to a valid state, use the following code, as shown in the example in C #:

IValidator Val;
foreach (val in validators) {
Val.isvalid = true;
}

To perform the entire validation sequence again, use the following code:

IValidator Val;
foreach (val in validators) {
Val.validate ();
}

If you have beta version 1 or later, you can also call the Validate method on only the Page object, which completes the same task. To make certain changes before validation, you can override the Validate method. This example displays a page that contains validators, which are on or off according to the value of the check box:

public class Conditional:page {
Public HtmlInputCheckBox Chksameas;
Public RequiredFieldValidator rfvalshipaddress;

protected override void Validate () {
Check only the arrival address (if different from the payment address)
bool enableship =!chksameas.checked;
rfvalshipaddress.enabled = enableship;
Perform validation now
Base. Validate ();
}
}


Client-side validation

If your page has client-side validation enabled, a completely different sequence of events occurs during the round trip. Client-side validation is implemented using client jscript®. You do not need any binary components to implement this validation.

Although the standardization of JScript languages is good, there is no widely used standard for document object models that interact with HTML documents in the browser (text object model, DOM). Therefore, the client's validation is only done in Internet Explorer 4.0 and later, because the authenticated object is the Internet Explorer DOM.

From the server's perspective, client-side validation only means that the validation control sends different content to the HTML. In addition, the sequence of events is exactly the same. Server-side checks are still performed. Although it may seem superfluous, it is important because:

Some validation controls may not support client script. There is a good example of this: if you want to use both the CustomValidator and the server validation functions, there is no client validation function.
Security considerations. Some people can easily get a page that contains a script, and then disable or change the page. You should not use scripts to prevent bad data from entering your system, but only for faster feedback from users. Therefore, if you want to use CustomValidator, you should not provide a client validation function that does not have a corresponding server validation function.
Each validation control can ensure that a standard client script block is sent to the page. In fact, this is just a small piece of code that contains references to code in the script library webuivalidation.js. This script library file contains all the logic for client authentication, which needs to be downloaded separately and stored in the browser's cache.

About the Script library

Because validating Web control scripts are in the script library, you do not have to send all client-validated code directly to the page, although that appears to be the case. The main scripting file references are similar to the following:

<script language= "JavaScript"
Src= "/_aspx/1.0.9999/script/webuivalidation.js" ></script>

By default, the script file is installed in the default root directory in the "_aspx" directory and is invoked with a script include directive relative to the root, which begins with a forward slash. This reference indicates that each individual object does not have to contain a script library, and that all pages on the same computer can reference the same file. You will notice that there is also a common language runtime version number in the path so that different runtime versions can run on the same machine.

If you look at your default virtual root directory, you will find the file and view its contents. The location of these files is specified in the Config.web file. The Config.web file is an XML file that is used for most asp+ settings. The following is the definition of the location in the file:

<webcontrols
clientscriptslocation= "/_aspx/{0}/script/"
/>

You are encouraged to read the script to get an insight into the events that occurred. However, it is recommended that you do not modify these scripts because their functionality is tightly linked to a specific runtime version. When versions are updated at run time, the scripts may also require appropriate updates, and you will either discard the changes or face problems with the script not working. If a specific project must change these scripts, back up the scripts, and then point your project to the backup file by using a private Config.web file instead of the location of the files. If the string contains the format directive "{0}", the runtime version number replaces the directive. It is a good idea to change the location to a relative or absolute reference.

Disabling authentication for clients

Sometimes you may not want to do client-side validation. If the number of input fields is small, client-side validation may be of little use. After all, you have a logic that requires a roundtrip server once at a time. You will find that information that appears dynamically on the client has a negative impact on your layout.

To disable client authentication, you should use the Page directive "Clienttarget=downlevel". This directive resembles the beginning of the following ASPX file:

<%@ Page language= "C #" Clienttarget=downlevel%>

The default value for this directive is "auto", which means that you only have client-side validation for Microsoft Internet Explorer version 4.0 or later.

Note: Unfortunately, in Beta 1, the directive is not just disabling validation, but it also causes all WEB controls to be processed using HTML 3.2 tags, which can produce unexpected results. The final version provides a better way to control the problem.

Client event Sequence

The sequence is the sequence of events that occurs when you run a page that contains client-side validation:

When the page is loaded into the browser, some initialization is required for each validation control. These controls are sent as <span> tags, and their HTML attributes are closest to the attributes on the server. Most importantly, all the input elements referenced by the validator are "hooked up" at this point. The referenced INPUT element modifies its client event to invoke the validation routine each time the input changes.
The code in the script library is executed when the user switches between fields using the TAB key. When a separate field changes, the validation condition is reassessed and the validator is visible or invisible as needed.
When a user attempts to submit a form, all validators are reassessed. If these validators are all valid, the form will be submitted to the server. If there is one or more errors, the following occurs:
The commit was canceled. The form is not submitted to the server.
All invalid validators are visible.
If a validation summary contains Showsummary=true, all errors from the validation control are collected and the contents are updated with those errors.
If a validation summary contains Showmessagebox=true, errors are collected and these errors are displayed in the client's information box.
Because client-side validation controls are executed each time the change is entered or committed, the validation controls are typically evaluated over two or two times on the client. Note that these validation controls will still be reassessed on the server after submission.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.