In-depth explanation of asp+ validation

Source: Internet
Author: User
Tags foreach definition empty extend functions object model valid versions
Asp+ 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.

Client API

There is a small API that can be used on the client to achieve a variety of effects in your own client code. Because some routines cannot be hidden, theoretically, you can take advantage of all the variables, attributes, and functions defined by the client-side validation script. However, many of these are implementation details that can be changed. The following summarizes the client objects that we encourage you to use.

Table 3. Client Object

Name Type description
The Page_isvalid Boolean variable indicates whether the page is currently valid. The validation script always keeps the variable up to date.
Page_Validators element Array This is an array that contains all the validators on the page.
The page_validationactive Boolean variable indicates whether validation should be performed. Set this variable to False to turn validation off programmatically.
IsValid Boolean Property Each client validator has this property, indicating whether the validator is currently valid. Note that in the PDC version, this property is mixed with case ("IsValid").


Bypassing client-side validation

One of the tasks you often need to do is to add a Cancel button or navigation button to the page. In this case, even if there is an error on the page, you might want to use the button to submit the page. Because the client button "onclick" event occurs before the "onsubmit" event of the form, it is possible to avoid submitting checks and bypassing validation. The following shows how to use the HTML Image control as the Cancel button to complete the task:

<input Type=image Runat=server
Value= "Cancel"
onclick= "Page_validationactive=false;"
Onserverclick=cmdcancel_click >

There is some confusion about using a Button or ImageButton control to perform this task because the OnClick event is assumed to be a server-side event with the same name. You should set this event in client script:

<asp:imagebutton Runat=server Id=cmdimgcancel
Alternatetext= "Cancel"
Onclick=cmdcancel_click/>

<script language= "JavaScript" >
document.all["Cmdimgcancel"].onclick =
New Function ("page_validationactive=false;");
</script>

Another way to resolve this problem is to set the Cancel button to a certain extent so that it does not trigger a commit event in client script when it returns. The HtmlInputButton and LinkButton controls are examples of this.

Special effects

Another common requirement is that, in the case of an error, some other effect is required in addition to the error message that is displayed by the validator itself. In this case, any modifications you make will need to be made at the same time on the server or client. Suppose you need to add a Label to change the color depending on whether the input is valid or not. The following is how to implement this task on the server:

public class Changecolorpage:page {
Public Label Lblzip;
Public RegularExpressionValidator valzip;

protected override void OnLoad (EventArgs e) {
Lblzip.forecolor = Valzip.isvalid? Color.Black:Color.Red;
}
}

All of the above methods are perfect, but as long as you modify the validation as described above, you will find that unless you do the same thing on the client, it will look very inconsistent. The validation framework allows you to avoid many of these double effects, but you cannot avoid other effects that you must implement simultaneously on both the client and the server. The following is a fragment that performs the same task on the client computer:

<asp:label Id=lblzip Runat=server
text= "Zip Code:"/>
<asp:textbox Id=txtzip Runat=server
Onchange= "Txtziponchange ();"/></asp:textbox><br>
<asp:regularexpressionvalidator Id=valzip Runat=server
Controltovalidate=txtzip
Errormessage= "Invalid ZIP code"
Validationexpression= "[0-9]{5}"/><br>

<script language=javascript>
function Txtziponchange () {
If client authentication is not active, no action is performed
if (typeof (page_validators) = = "undefined") return;
Change the color of a label
LblZip.style.color = Valzip.isvalid? "Black": "Red";
}
</script>

Beta 1 Client API

For beta version 1, some functions that can be invoked from client script may cause other situations.

Table 4. Functions that are called from client script

Name Description
Validatorvalidate (Val) takes a client validator as input. Causes the validator to check its input and update its display.
Validatorenable (Val, enable) Gets a client validator and a Boolean value. Enable or disable the client validator. If disabled, the client validator is not evaluated and the client validator is always displayed as valid.
Validatorhookupcontrol (Control, Val) gets an input HTML element and a client validator. Modify or create a change event for the element to update the validator when it changes. This function is appropriate for custom validators that are based on multiple input values.


Its special purpose is to enable or disable the validator. If you want validation to take effect only in specific cases, you may need to change the activation state on both the server and the client, otherwise you will find that the user is unable to submit the page.

The following example adds a field that is validated only when a check box is unchecked.

public class Conditional:page {
Public HtmlInputCheckBox Chksameas;
Public RequiredFieldValidator rfvalshipaddress;
protected override void Validate () {
bool enableship =!chksameas.checked;
rfvalshipaddress.enabled = enableship;
Base. Validate ();
}
}

The following are the client-equivalent code:

<input Type=checkbox Runat=server Id=chksameas
Onclick= "Onchangesameas ();" > Same as payment address <br>
<script language=javascript>
function Onchangesameas () {
var enableship =!event.srcelement.status;
Validatorenable (rfvalshipaddress, enableship);
}
</script>


Validation rules and useful error messages

Each validator displays specific error messages about specific conditions for a particular control. There are some rules that confirm whether it is valid, and you may be somewhat confused as a developer, but these rules are necessary if you want to generate error messages that are actually helpful to the user.

All empty validators (except RequiredFieldValidator) are considered valid. If a null value is not valid, you typically need a requiredfieldvalidator and a different validator. You need to do this because, in general, you always want to display a different error message to the null validator and effectivity. You can also use ambiguous information, such as "You must enter a value, and the value must be between 1 and 10."

Another special rule that is used when the input field cannot be converted to the specified data type is related to CompareValidator and RangeValidator. The process of assessing the effectiveness of the CompareValidator that has been specified ControlToCompare is similar to the following:

Valid if the input field referenced by ControlToValidate is empty.
Invalid if the input field referenced by ControlToValidate cannot be converted to the desired data type.
Valid if the input field referenced by ControlToCompare cannot be converted to the desired data type.
The input field is converted to the desired data type and compared.
The third step seems to be somewhat counterintuitive. This is evaluated because it is difficult to write meaningful error messages for the validator if the validator checks the validity of multiple fields at the same time. You should use a standalone validator to report an error condition in the ControlToCompare input field. RangeValidator work in a similar way, with maximum and minimum properties.


Functions of Enabled, Visible and Display properties

The difference between the Enabled, Visible, and Display properties of the validator may not be very obvious.

Display=none can be used to specify that the validator does not display anything directly, but still evaluates it, still affects overall effectiveness, and can still place errors in the summary on both the client and the server. For client-side validation, these values determine whether the validator is turned on or off using the visibility style attribute or using the display style attribute. For server-side validation, display=dynamic indicates that no content is displayed when the input is valid, and display=static indicates that a blank space ("") appears without a newline. The last setting is used so that cells that contain only validators in the table are not collapsed to show nothing when they are valid.

Why not just use Visible=false to make the validator invisible? In asp+, the Visible property of a control has many meanings: the Visible=false control is not processed at all to be displayed or displayed. It is precisely because of this meaning that the visible=false of the validator means that not only nothing is displayed, but it cannot be used. This validator is not evaluated, does not affect the validity of the page, and does not place the error in the summary.

Enabled is neutral. For most cases, the effect of Enabled=false and Visible=false is exactly the same. In Beta 1 or later, there is an important difference: In client-side validation, a disabled validator is still sent to the browser, but is disabled. You can use the Validatorenable function in client script to activate the validator.

When using Visible or Enabled control for validation, be aware of the order of events on the above servers. Either make a change before validating it or verify it after the change. Otherwise, their IsValid values do not reflect the changes to the property.


CustomValidator control

The easiest way to extend the validation framework is to use the CustomValidator control. The control can be used to perform validation that cannot be performed by other validation controls, or to perform authentication that requires access to information on the server, such as a database or WEB service.

If you add a CustomValidator that defines only one server validation function, you will notice that the validator does not participate in client-side validation. When users switch between fields by using the TAB key, CustomValidator is not updated and requires a roundtrip server to perform its validation. If you want to use CustomValidator to perform a check that does not require information on any server, you can also use the ClientValidationFunction property to have the validator fully participate in client-side validation. Suppose you provide a clientvalidationfunction, ideally, you should perform the exact same check as the server authentication handler. In practice, however, only part of the validation is performed. The client-side validation function does not exceed the validation performed on the server because it is easy for the hacker to bypass the validation function.

The following is a simple example of using CustomValidator on both the client and the server to check if the input is even. The following describes the server functions (in C #):

public bool Servervalidation (object source, string value) {
try {
int i = Int. FromString (value);
Return ((i% 2) = = 0);
catch {
return false;
}
}

Here's how the function is declared on the client and a client-side validation function that performs the same check. This is usually a JScript form, but if your goal is microsoft®internet Explorer, you can also use the vbscript® form.

<asp:customvalidator id= "CustomVal2" Runat=server
Errormessage= "Number can not be removed by 2!" "
Controltovalidate= "Txtcustomdata"
Onservervalidationfunction=servervalidation
clientvalidationfunction= "Checkeven"/><br>
Data Field: <asp:textbox id= "Txtcustomdata" runat= "Server"/>
<script language=javascript>
<!--
function Checkeven (source, value) {
var val = parseint (value, 10);
if (isNaN (val))
return false;
Return ((val% 2) = = 0);
}
-->
</script>

Here are some considerations for using CustomValidator:

Similar to all other validation controls (except RequiredFieldValidator), CustomValidator is considered valid if the input field is blank.
If you use an older browser, or if you turn off client authentication, you will not be able to invoke the client validation function. Before you define this function, you do not have to check the functionality of the browser you are using, but you need to make sure that the browser does not cause scripting errors because of the definition. Be sure to make your client code an HTML annotation, as shown in the following example.
Two parameters are passed to your client function, corresponding to the arguments passed to the server function. The first is the client validator element, and the second is the control value specified by ControlToValidate. On the client, however, you can choose not to define parameters for the function, which will work as well.
If you use the BETA1 version or later, you can leave ControlToValidate blank. In this mode, the server function is always triggered once per round trip, and the client function always triggers once every attempt to commit. You can use this attribute to validate controls that other methods cannot validate, such as CheckBoxList or a separate radio button. Use this method if the condition is based on multiple controls, and you do not want the user to evaluate the condition by using the TAB key to switch between the fields on the page.
Another option in beta version 1 or later is the change event that hooks multiple controls. The method is to add some inline scripts that call the client function Validatorhookupcontrol, as described above.

Which controls can be validated?

To enable a control to be referenced by a validation control, the control must have a validation property. All controls that can be validated have the ValidationPropertyAttribute property, which indicates the properties that should be read when validating. If you write your own control, you can make the control participate in validation by providing one of the attributes to specify the property to use.

For the validation to work correctly on the client, the property must correspond to the value attribute of the HTML element that is displayed by the client. Many complex controls, such as DataGrid and Calendar, have no value on the client and can only be validated on the server. Therefore, only controls closest to the HTML element can participate in validation. In addition, the control must have a single logical value on the client. Therefore, RadioButtonList can be validated, but CheckBoxList is not possible.


End

The above explanation of asp+ validation may be beyond what you need to know. Enjoy it!







--------------------------------------------------------------------------------
Please browse this site with the IE4.0 version 800 * 600
©2001 Microsoft Corporation All rights reserved. All rights reserved. Usage rules.


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.