Summary: Detailed explanations to the use of ASP+ verification web control.
Table of contents
Brief introduction
getting Started
When does it happen?
Verification sequence on the server side
Client verification
Effective rules and useful error information
ENabled, Visible and Display Properties' functions
CustomValidator control
Which controls can be verified?
End
------------------------------------------------ ----------------------------------------------------------------------------
Brief introduction
This article explains the working method of ASP+ verification control in detail. If you want to generate a complex page that contains the verification control, or to expand the verification framework, it is recommended that you read this article. If you want to learn to use the verification control or decide whether to use the verification control, see "ASP+ User Enter Verification (English)".
getting Started
We know that it is important to understand verification during the entire ASP+ development process. Look at most of today's commercial web sites, you will find that there are many forms in these sites, which are obviously executed by executing a large number of handwritten code. Writing verification code is not an interesting job. If you write a code to display the data table or dynamically generate charts, it may be very attractive, but no one can confirm with his colleagues that this "cool" method can prohibit the empty value in the name field.
For other reasons, the verification of web applications is also very troublesome. HTML 3.2 has a lot of restrictions on the content you can control or feedback that you can get from the user, so it cannot be applied to the techniques that can be used on a more fulfilling client, such as prohibiting users from entering certain characters or making a sound. Using browser script may produce more powerful verification. However, this method is difficult to confirm, because the customer's browser is not necessarily script, and malicious users can bypass it. Therefore, in order to ensure the safety of the site, it is necessary to perform the same inspection of the server.
When developing ASP+, our original intention is to use only one control to process verification. It may have been a TextBox control that can show wrong. But when it was designed, I found that this desire could not be achieved. We have researched a large number of data input forms to find a solution that can be applied to as many forms as possible. We found that the data input table has many interesting features:
Although error information or icons are often adjacent to the input elements, they are almost always located in different cells of the table.
There is often a area on the page to summarize all errors.
Many sites include client scripts to provide faster feedback while preventing traveling between the server in vain.
Many sites containing client scripts display information boxes when there is an error.
Not only will the text input be verified, but also the drop -down list and single -selection button will be verified.
If a field is empty, the site usually shows different information or icons when the entry is invalid.
Many effective examinations can be well replaced by commonly used expressions.
Verification is usually based on comparison results between two inputs.
90% or more than 90% of the verification tasks are some common operations, such as checking name or postal code. Most sites still seem to be repeating these tasks.
Because the difference between sites is usually too large, a perfect solution cannot be obtained to handle all the verification tasks of each site.
Considering all the above situations, the final solutions include five verification device controls, ValidationSummary controls, and integration with Page objects. At the same time, it is obvious that the solution needs to be expanded, and a API is needed to cooperate on the client and server.
We found that we seemed to need a larger toolbox during the various verifications of research. In most component environments, such as Microsoft & Reg; Activex & Reg;, we may have tried to integrate the functions of all verification controls into a control to process different attributes in different modes. Fortunately, there is a magical inheritance in Microsoft & Reg; .NET framework, which can provide a set of controls to verify specific attributes, because the extra workingload required for each new control is very small.
Most of these controls are implemented in their public parent -level Basevalidator. You can also complete various tasks from Basevalidator or other controls. In fact, even if Basevalidator is too lazy to achieve its own text attributes, it is inherited from Label attributes.
When does it happen?
It is very effective to understand the event sequence when processing the page containing the page of the web control. If a verification condition is optional, you need to accurately understand when the client and server are verified. If you want to write a verification routine yourself, it may be very time -consuming or side effects. At the same time, it is also important to understand the timing of calling verification routine.
First, let's take a look at the server.
Verification sequence on the server side
It is important to understand the validity period of the page. If you are accustomed to processing the form in the Visual Basic or similar functional client tools, you need to spend a certain time to understand. All objects on the page and page are not effective when interacting with users, although sometimes this is the same.
The following is a simplified event sequence when visiting a page for the first time:
Create a page and its control based on the ASPX file.
Triggering the page_load event.
Page and control attributes are stored in a hidden field.
Pages and controls are converted to HTML.
Discard everything.
Now, when the user clicks a button or a similar control, it will return to the server and then execute a similar event sequence. This sequence is called the return sequence:
Create a page and its control based on the ASPX file.
Restore the page and control attributes from the hidden field.
Enter the update page control according to the user.
Triggering the page_load event.
Trigger changes notification events.
Page and control attributes are stored in a hidden field.
Pages and controls are converted to HTML.
Discard everything again.
Why don't we keep all objects in memory? Because web sites established with ASP+ cannot handle very large number of users. Therefore, the server's memory only retains the content to be processed immediately.
When is the server -side verification? When obtaining page information for the first time, server -side verification will not be performed at all. Most end users are very serious. We allow users to confirm whether the information filled in in the form is correct, and then we use the red text to inform the user to fill in the wrong information.
In the return event sequence, verification will be performed between step 3 and step 4. In other words, verification is after the data loading control attributes from the user, but before most of the number of code execution. This means that when writing user events, it can usually be used for verification. Under normal circumstances, you will want to do this.
The disadvantage of verification at that moment is: If you want to modify some attributes that affect the verification by programming, it will be too late. For example, you will find that if you use the code to enable or disable the attributes of the verification control or modify the verification control, you will not see any effect before processing the page. This problem can be avoided through the following two methods:
Modify the attribute before verification.
Re -verify the control after the attribute change.
Both methods need to use effective verification attributes and methods on the Page object.
Page API
Page objects include some important attributes and methods related to the server -side verification. Table 1 summarizes these attributes and methods:
Table 1. Page object's attributes and methods
Attribute or method description
The Isvalid attribute is the most useful attribute. This attribute can check whether the entire form is effective. This check is usually performed before updating the database. Only all the objects of Validators are valid, the attribute is true, and the value is not stored in the cache.
Validators attributes The collection of all verification objects of this page. This is a collection of objects that implement the IVALIDATOR interface.
The value method calls a method when verification. The default execution method on the Page object is to turn to each verification device and require the verification device to evaluate itself.
The Validators collection is very useful for many tasks. This set is a collection of objects that implement the IVALIDATOR interface. The reason why I use the object is not the control of the control because the Page object only pays attention to the Ivalidator interface. Since all the verifications are usually used to achieve some visual controls of Ivalidator, anyone should be able to use any verification object and add the verification object to the page.
Ivalidator interface contains the following attributes and methods:
Table 2. The attributes and methods of the ivalidator interface
Attribute or method description
The ISVALID attribute pointed out whether the validity test performed by a separate verification object has passed. You can manually change the value after verification.
ErrorMessage attribute introduces the error to verify the object to be verified and the errors that may be displayed to the user.
The Validate method is checked for the validity of the verification object to update its ISVALID value.
You can use this interface to perform some interesting tasks. For example, to reset the page to an effective state, use the following code (such as the example shown in C#):
Ivalidator value;
FOREACH (Val in Validators) {
valuevalid = TRUE;
}
To re -execute the entire verification sequence, use the following code:
Ivalidator value;
FOREACH (Val in Validators) {
Val.validate ();
}
If you have Beta 1 edition or higher versions, you can also call the value method only for the Page object, so that the same task can be completed. To make some changes before verification, the value method can be covered. This example shows a page containing the verification device, which is opened or off according to the value of the check box:
Public Class Conditional: Page {
public htmlinputcheckbox chksameas;
public researchFieldValidator rfvalshipaddress;
Protected Override Void Validate () {) {)
// Just check the delivery address (if different from the payment address)
BOOL Enableship =! Chksameas.checked;
rfvalshipaddress.enabled = enableship;
// Now executing verification
base.validate ();
}
}
Client verification
If your page is enabled by client verification, a completely different event sequence will occur during the round trip. The client's verification uses the client JScript & reg; implemented. The verification does not require any binary components.
Although the standardization of the JSCRIPT language is well done, the document object model (DOM) used in the HTML documentation in the browser (DOM) has not widely used standards. Therefore, the client verification is only performed in the Internet Explorer 4.0 and higher versions, because the verified object is the Internet Explorer DOM.
From the perspective of the server, the verification of the client only means that the verification control sends different content to HTML. In addition, the incident sequence is exactly the same. The server -side check is still performed. Although it seems redundant, it is very important because:
Some verification controls may not support the client script. There is a good example: if you want to use the CustomValidator and server verification functions at the same time, but there is no client verification function.
Safety precautions. Some people can easily get a page containing a script, and then disable or change the page. You should not use your script to prevent bad data from entering your system, but only for users to get faster feedback. Therefore, if you want to use CustomValidator, you should not provide a client verification function without corresponding server verification functions.
Each verification control can ensure that a standard client script block is sent to the page. In fact, this is just a small part of the code, which contains a reference to the code in the script library webuivalidation.js. This script library file contains all logic verified by the client. This file needs to be downloaded separately and can be stored in the cache of the browser.
About script library
Because the verification of the web control script is in the script library, the code verified by all clients is not necessary to directly send it to the page, although it seems to be done on the surface. The main script file references is similar to the following:
<script language = javascript
src =/_ASPX/1.0.9999/Script/Webuivalidation.js> </Script>
By default, the script file will be installed in the default root directory in the _ASPX directory, and uses a script Include instruction to be called, which starts with a positive diagonal line. The reference shows that each individual object does not need to include the script library, and all pages on the same computer can reference the same file. You will notice that there is also a public language version number in this path, so that different runtime versions can run on the same computer.
If you look at your default virtual root directory, you will find the file and view the content. The position of these files is specified in the config.web file. Config.web file is an XML file for most ASP+ settings. The following is the definition of the position in this file:
<webcontrols
ClientScriptsLocation =/_ ASPX/{0}/script/
/>
Encourage you to read the script so that you can understand the events that occur in depth. However, it is recommended that you do not modify these scripts, because their functions are closely linked to specific runtime versions. When the version is updated, these scripts may also need to be updated accordingly. You will give up changes, or face the problem of not working. If specific projects must be changed, first backup these scripts, and then point your project to the backup file, the method is to use a private config.web file to replace the position of these files. If the string contains the format command {0}, the version number will replace the instruction when the runtime version number will be replaced. It is best to change this position to a relative reference or absolute reference.
Disable client verification
Sometimes you may not want to verify clients. If the number of input fields is small, the client verification may not be very useful. After all, you have to have a logic that requires one round -trip server every time. You will find that the dynamic information on the client will have a negative impact on your layout.
To disable client verification, use the page instruction clientTarget = DOWNLEVEL. This instruction is similar to the beginning of the ASPX file:
< %@page Language = C# ClientTarget = DOWNLEVEL %>
The default value of this instruction is Auto, indicating that you only verify the client of the Microsoft Internet Explorer 4.0 or higher versions.
Note: Unfortunately, in Beta 1, this instruction is not just disabled for verification, and at the same time, all web controls use HTML 3.2 tags to process, which may have unexpected results. The final version provides a better way to control this problem.
Client event sequence
This sequence is an event sequence that occurs when the page containing the client verification:
When loading the browser on the page, you need to initialize each verification control. These controls are sent as the <span> mark, and their HTML features are closest to the features on the server. Most importantly, all input elements referenced by the verification device will be "hanged" at this time. The referenced input element will modify its client event to call the verification routine when entering the change.
The code in the script library will be executed when the user uses the TAB key to switch between each field. When a certain independent field is changed, the verification conditions will be re -evaluated, and the verification device will be visible or invisible as needed.
When the user tries to submit the form, all the verifications will be evaluated. If all these verificationrs are effective, the form will be submitted to the server. If there is an error in one or more places, the following situation will occur:
The submission was canceled. The form is not submitted to the server.
All invalid verifications are visible.
If a verification summary contains Showsummary = True, all errors from the verification control will be collected and the content is updated with these errors.
If a verification summary contains ShowmessageBox = TRUE, it will collect errors and display these errors in the client's information box.
Because the client verification control is executed when entering or when. Please note that after submission, these verification controls will still be re -evaluated on the server.
Client API
There is a small API that can be used on the client to achieve various effects in your own client code. Because some routine cannot be hidden, in theory, you can use the client to verify all variables, characteristics, and functions defined by the client. However, many of them can be changed. The following summarizes the client object we encourage you to use.
Table 3. Client object
Name type description
Page_isValid Boolean variable pointed out whether the page is currently valid. Verifying scripts always keep the variable latest.
Page_validator element array This is an array containing all the verifications on the page.
Page_validationActive Boolean variables indicate whether it should be verified. Set this variable to FALSE can be proofed by programming.
ISVALID BOOLEN attributes each client verification device has the property, pointing out whether the verification device is currently valid. Please note that in the PDC version, this attribute is mixed with Isvalid.
Bypassing client verification
One task you often need to execute is to add the "Cancel" button or navigation button on the page. In this case, even if there are errors on the page, you may also want to use the button to submit the page. Because the client button onClick event occurs before the onSubmit event of the form, it may avoid submitting inspection and bypassing verification. 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;
onServerClight = cmdcancel_click>
Use the Button or ImageButton control to execute some confusion, because the OnClick event assumes that it is a server -side event with the same name. You should set this event in the 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 method to solve this problem is to set a certain settings of the "Cancel" button so that it will not trigger the submission event in the client script when returning. HTMLINPUTBUTTON and LinkButton controls are the examples.
Special effect
Another common requirement is that in addition to error information displayed by the verification device itself, some other effects are needed. In this case, any modification you make needs to be carried out at the same time on the server or client. Suppose you need to add a label to change the color according to whether the input is valid. The following is how to implement this task on the server:
Public Class ChangecolorPage: Page {
public label lblzip;
public regulaxpressionvalidator value;
ProteCted Override Void Overoad (EventArgs E) {{
lblzip.Forecolor = valzip.isvalid? Color.black: color.red;
}
}
All the above methods are perfect, but as long as you modify the verification above, you will find that unless you perform the same operation on the client, it will look very inconsistent. The verification framework will allow you to avoid many such dual effects, but it cannot avoid other effects you must achieve at the same time on the client and server. The following is a fragment that performs the same task on the client:
<asp: label id = lblzip runat = server
text = zip code:/>
<ASP: Textbox ID = TXTZIP Runat = Server
onChange = txtziponchange (); /> < /asp: Textbox> <br>
<ASP: RegulaRXPRESSIONVALIDIDATOR ID = VALZIP RUNAT = Server
Controltovalidate = txtzip
errorMessage = invalid postal code
ValidationXpression = [0-9] {5} /> <br>
<script language = javascript>
Function txtziponchange () {{) {
// If the client verification is not in the activity, it will not perform any operation
ifof (page_validators) == Undefined) Return;
// Change the color of the label
lblzip.style.color = valzip.isvalid? Black: red;
}
</script>
Beta 1 client API
For Beta 1 edition, some functions that can be called from the client script will cause other situations.
Table 4. Function from client script call
Name Description
Validatorvalidate (Val) uses a client verification device as input. Make the verification device check its input and update its display.
ValidatoreNable (Val, Enable) obtain a client verification device and a Boolean value. Enable or disable the client verification device. If it is disabled, the client verification device will not be evaluated, and the client validator will always be valid.
ValidatorHookupControl (Control, Val) obtained an input HTML element and a client verification device. Modify or create the Change event of the element so that the verification device can be updated during the change. This function is suitable for customized verifications based on multiple input values.
Its special purpose is to enable or disable the verification device. If you want to verify that you only take effect in specific circumstances, you may need to change the activation status at the same time on the server and clients, otherwise you will find that the user cannot submit the page.
The following is the above example plus a field. This field will be verified only when the selection of a check box is canceled.
Public Class Conditional: Page {
public htmlinputcheckbox chksameas;
public researchFieldValidator rfvalshipaddress;
Protected Override Void Validate () {) {)
BOOL Enableship =! Chksameas.checked;
rfvalshipaddress.enabled = enableship;
base.validate ();
}
}
The following is the code of the client equivalent:
<input type = checkbox runat = server id = chksameas
Onclick = Onchangesameas ();> The same as the payment address <br>
<script language = javascript>
Function onchangesameas () {
var entlesHip =! Event.srcelement.status;
Validatorenable (RFValshipaddress, Enableship);
}
</script>
Effective rules and useful error information
Each verification device shows specific error information about specific conditions in specific controls. There are some rules that confirm whether it is valid. At first, you may be confused as a developer, but if you want to generate error information with actual help to users, these rules are necessary.
All empty verifications (except for RequiredFieldValidator) are considered valid. If an empty value is invalid, you usually need a RequiredFieldValidator and an other verificationer. You need to do this, because in general, you always want to show different error information on the empty verification device and effectiveness. You can also use unclear information, such as "you must enter a value, and this value must be between 1 and 10".
Another special rules used when the input field cannot be converted into a specified data type is related to compareValidator and Rangevalidator. The validity assessment process of the compareValidator of ControltocomPare specifies the validity assessment process is as described below:
If the input field referenced by Controltovalidate is empty, it is effective.
If the input field referenced by Controltovalidate cannot be converted to the required data type, it is invalid.
If the input field referenced by Controltocompare cannot be converted to the required data type, it is valid.
The input field is converted to the required data type and compares.
The third step looks a little inconsistent. The reason for this is because if the verification device checks the effectiveness of multiple fields at the same time, it is difficult to write meaningful error information for the verification device. A independent verification device should be used to report the error situation in the ControltocomPare input field. Rangevalidator has similar working methods, with Maximum and Minimum properties.
ENabled, Visible and Display Properties' functions
The difference between the Enabled, Visible and Display properties of the verification device may not be very obvious.
Display = None can be used to specify that the verification device does not directly display any content, but still evaluates, still affects the overall effectiveness, and can still put errors in the summary of the client and server. For client verification, these values are determined to use the visible style characteristics or use the display style characteristics to open or close the verification device. For server -side verification, Display = Dynamic means that the input does not display any content when the input is valid, and Display = Static represents a space that does not change. The last setting is to be folded into no content when the cell that contains only the verification device in the table is valid.
Why not only use Visible = false to make the verification device visible? In ASP+, the Visible attribute of the control has many meanings: the control of Visible = FALSE will not be processed or displayed at all. It is precisely because of this meaning that the Visible = FALSE of the verification device means that not only does not display any content, but also cannot be used. This verification device will not be evaluated, will not affect the validity of the page, nor will it be put in the abstract.
Enabled is neutral. In most cases, the effect of enabled = false and visible = false is exactly the same. In the Beta 1 edition or higher version, there is an important difference: in client verification, the disabled verification device will still be sent to the browser, but it is in a disabled state. You can use the ValidatoreNable function in the client script to activate the verification device.
When using Visible or Enabled to control whether to verify, pay attention to the order order on the above server. Or change before verification, or re -verify after the change. Otherwise, their ISVALID values will not reflect changes to attributes.
CustomValidator control
The easiest way to extend the verification framework is to use the CustomValidator control. This control can be used to perform verifications that other verification controls cannot be performed, but they can also execute verifications that need to access information on the server (such as databases or web services).
If the CustomValidator with only one server verification function is added, you will notice that the verification device does not participate in client verification. When the user switches between each field with the Tab key, the CustomValidator will not be updated, and the round -trip server needs to perform its verification at one time. If you want to use the CustomValidator to perform a check that does not require any information on the server, you can also use the clientValidationFunction property to make the verification device completely participate in client verification. Suppose you provide a ClientValidationFunction. Ideally, you should perform exactly the same inspection as the server verification processing process. But in fact, it is only a part of the verification. The verification of the client verification function does not exceed the verification of executing on the server because hackers can easily bypass the verification function.
The following is a simple example of using CustomValidator on the client and server, only check whether the input is even. Let's introduce the server function (in C#):
{partialive service) {position
try {
int i = int.fromstring (value);
Return ((i % 2) == 0);
} Catch {
Return false;
}
}
The following is the declaration method of the function on the client, and a client verification function that performs the same check. This is usually a JScript form, but if your goal is Microsoft & Reg; Internet Explorer, you can also use VBScript & reg; form.
<ASP: CustomValidator ID = CustomVal2 Runat = Server
ErrorMessage = numbers cannot be removed!
Controltovalidate = txtCustomdata
onSerValIdationFunction = Servervalidation
clientValidationFunction = Checkeven /> <br>
Data Field: <Asp: Textbox ID = TXTCUSTOSDATA RUNAT = Server />
<script language = javascript>
<!--
Function Checkeven (Source, Value) {{
var value = PARSEINT (VALUE, 10);
if (ISNAN (Val))
Return false;
Return ((Val % 2) == 0);
}
//->
</script>
Here are some precautions using CustomValidator:
Similar to all other verification controls (except for RequiredFieldValidator), if the input field is empty, it is considered that the CustomValidator is effective.
If the older browser is used or the client verification is closed, the client verification function cannot be called. Before defining the function, you don't have to check the function of the browser used in the browser, but you need to ensure that the browser does not cause script errors due to definition. Be sure to make your client code as an annotation of HTML, as shown in the following example.
Two parameters are passed to your client function and correspond to the parameters passed to the server function. The first is the client verification device element, and the second is the control value specified by the controltovalidate. However, on the client, you can choose not to define parameters for the function, which will work normally.
If you use Beta1 or higher versions, you can keep Controltovalidate as empty. In this mode, the server function will always trigger a round -trip round trip, and the client function will always be triggered every time you try to submit it. You can use this feature to verify the controls that other methods cannot verify, such as CheckBoxList or separate radio buttons. If the condition is based on multiple controls, and you do not want the user to evaluate the condition when switching between each field on the page, you can use this method.
Another option in Beta 1 or higher version is the Change event of multiple controls. The method is to add some embedded scripts that call the client function ValidatorHookupControl, as described above.
Which controls can be verified?
To enable the control to be verified by the control reference, the control must have verified attributes. All verified controls have validationPropertyattribute properties, which indicate the attribute that should be read during verification. If you write your own control, you can specify the attributes to be used by providing one of them, so that the control is involved in verification.
To enable the verification to be carried out normally on the client, the attribute must correspond to the value characteristics of the HTML element displayed by the client. Many complicated controls (such as DataGrid and Calendar) are not worth the client and can only be verified on the server. Therefore, only controls closest to HTML elements can participate in verification. In addition, control must have a single logic value on the client. Therefore, RadiobuttonList can be verified, but CheckBoxList cannot.
End
The above -mentioned explanation of ASP+ verification may have exceeded the content you want to understand. Enjoy it!
------------------------------------------------ ----------------------------------------------------------------------------
Please use IE4.0 above version 800 * 600 views on this site
& Copy; 2001 MicroSoft Corporation All rights reserved. Keep ownership. Use regulations.
Collect the most practical webpage special effect code!