ASP.net 2.0 server control implementation validation controls

Source: Internet
Author: User
Tags alphabetic character define bool contains expression implement include valid
Asp.net| Server | control

To better create interactive Web applications, to enhance application security (for example, to prevent scripting intrusions, etc.), developers should provide validation capabilities for the parts of the user input. In the past, the input validation function is basically written by the client script to complete this implementation is cumbersome and prone to errors. With the development of technology, ASP. NET technology overcomes these drawbacks by providing a series of validation controls, such as RequiredFieldValidator, CompareValidator, RangeValidator, and so on. Using these validation controls, developers can add input validation to Web pages, such as defining validation rules, defining error message content to be displayed to the user, and so on. Typically, ASP. NET provides validation controls that meet the needs of most Web applications, however, in some cases, built-in validation controls cannot fulfill the specific requirements of application requirements for data entry. To remedy this shortcoming, ASP.net 2.0 defines an extensible validation framework that can be used in control development. Developers can define validation controls themselves by using this validation framework. This article introduces important aspects of implementing validation controls, including a built-in validation control overview, validation frameworks, and so on.

   1. Built-in validation Controls Overview

The validation control completes the ability to validate the input data. By associating a validation control with an input control, developers can add input validation to a Web page. In addition, the methods for customizing validation rules and the content and display of custom error messages are provided. This section provides an overview of the ASP.net built-in validation controls.

ASP.net 2.0 contains 5 built-in validation controls: RequiredFieldValidator, CompareValidator, RangeValidator, RegularExpressionValidator and CustomValidator, these controls derive directly or indirectly from System.Web.UI.WebControls.BaseValidator. Each validation control performs a specific type of validation and displays a custom message when validation fails. The 5 validation controls are briefly described below.

(1) RequiredFieldValidator Control

The control is used to ensure that a value is included in the control being validated.

(2) CompareValidator control

The control uses a comparison operator (less than, equal to, greater than, and so on) to compare user input to a constant value or to a property value of another control.

(3) RangeValidator control

This control is used to check whether the user's input is within a specified upper or lower limit. You can check the range of numeric pairs, alphabetic character pairs, and date pairs.

(4) RegularExpressionValidator control

This control is used to check whether the item matches the pattern defined by the regular expression. This type of validation allows you to check for predictable sequences of characters, such as ID numbers, e-mail addresses, phone numbers, postal codes, and so on.

(5) CustomValidator control

This control is used to check user input using validation logic that you write yourself. This type of validation allows you to check the values that are exported at run time.

In addition to the built-in validation controls above, ASP.net 2.0 provides a control validationsummary for displaying an error message profile. The purpose of the control is to display the error messages from all validation controls on the page together in one location, such as a message box or a list of error messages. The ValidationSummary control does not perform validation, but it can be used with all validation controls, and more accurately, ValidationSummary can work with the 5 built-in validation controls as well as the custom validation controls to complete the validation function.

To use validation controls on a Web page, we need to be aware of several key aspects of the following.

First, you associate the validation control with the input control, and then define the related properties based on the characteristics of the different types of validation controls. For example, all validation controls have to be associated with the Contrltovalidate property to define the error message content through the ErrorMessage property, and for the scope check control RangeValidator, You must define the MaximumValue and MinimumValue properties to specify the minimum and maximum values for a valid range, and for a pattern-matching control RegularExpressionValidator, You must use the ValidationExpression property to specify the regular expression used to validate the input control. The use of the above description is likely to allow an input control to associate multiple validation controls, which is allowed in ASP.net 2.0.

Second, ASP.net 2.0 provides a new property validationgroup for the validation control. Developers can use this property to associate a single control with a validation group, and then use multiple ValidationSummary controls to collect and report errors for those groups. If no validation group is specified, the validation function is equivalent to the validation feature in ASP.net 1.x. If more than one validation group is specified in multiple controls, multiple validation summary controls must be displayed because a validation summary displays only validation errors for one group. A control that is sent back to the server and currently has the CausesValidation property also introduces this ValidationGroup property, which determines the group of controls that should be validated when the control causes a postback. If no validation group is specified, the default group is validated and the default group consists of all validators that do not have an explicit assignment group.

Finally, once the validation controls are properly included in the Web page, developers can use their own code to test the state of a page or a single validation control. For example, test the IsValid property of a validation control before using the input data. True to indicate that the input data is valid, false to indicate an input error, and to display an error message. For Web pages, the IsValid property of the page class is set to true only if all the validation controls are IsValid true, or False if all input data conforms to the validation criteria. In addition, in page-level validation, ASP.net 2.0 also provides two new ways to support validation capabilities. One is the Getvalidators method from the page class that retrieves the validator that belongs to the specified validation group. There is also an overload of the Validate method from the page class that allows validation groups to be used as parameters.

   2. Validation control Implementation Mechanism

Typically, you can meet the needs of most applications by using the 5 built-in validation controls of ASP.net 2.0. However, in order to increase the flexibility of development and meet the requirements of different Web applications, asp.net 2.0 has an extensible validation framework built into it. The framework defines the basic implementation rules for both the server side and the client. Developers can use this extensible validation framework to design their own validation controls to implement new design rules, depending on the application.

(1) server-side implementation mechanism

Not all Web server controls support validation controls. Standard controls that can be validated with validation controls include TextBox, ListBox, DropDownList, RadioButtonList, HtmlInputText, HtmlInputFile, HtmlSelect and HtmlTextArea, FileUpload and Htmlinputpassword. These controls that support validation controls have a common feature, that is, the metadata contains System.Web.UI.ValidationPropertyAttribute. ValidationPropertyAttribute defines the metadata attributes that a control uses to identify validation properties. In addition, if the custom control class that derives from the above control needs to support validation, then the ValidationPropertyAttribute must be defined before the control class, so that the control can be used as the validation target control. In implementing a custom validation control, developers must first understand the contents of the validation target control described above before they can better develop the control.

To implement a custom validation control, ASP.net 2.0 provides 3 important objects: (1) System.Web.UI.IValidator; (2) System.Web.UI.WebControls.BaseValidator; (3) System.Web.UI.WebControls.CustomValidator. The above three are closely related, the verification framework composed of them has strong flexibility and scalability. The IValidator interface is the basis for a validation framework, and any class that implements that interface can act as a validator. BaseValidator is an abstract base class that implements the IValidator interface and inherits the System.Web.UI.WebControls.Label control. Typically, custom validation controls derive from the class. CustomValidator is actually a validation control that developers can use to add custom validation logic. For a better description of the validation framework, the above 3 objects are described below.

The IValidator interface is defined as follows:

public interface IValidator
{
String ErrorMessage {get; set;}
BOOL IsValid {get; set;}
void Validate ();
}


The members of the IValidator interface include 1 methods and 2 properties. The ErrorMessage property is used to get or set the error message that is generated when a conditional validation fails. IsValid property when implemented by a class, gets or sets a value that indicates whether the content entered by the user in the specified control passes validation. When the Validate method is implemented by a class, it evaluates the conditions it checks and updates the IsValid property. For developers, if you implement a generic validator rather than a validation control, you can do so by implementing the interface. The reason for this is that the implementation of the validation framework is distributed in the page class, the BaseValidator class, and the validation target control. Dependencies between these classes do not allow arbitrary implementation of the IValidator interface. For implementing custom validation controls, the recommended approach is to inherit the BaseValidator class.

BaseValidator is the most important part of the validation framework. This class derives from the label class and implements the IValidator interface. Both the built-in validation control and the custom validation control must derive from the BaseValidator class. This class implements the common properties that all validation controls must implement. Some common validation properties are described below.

· ControlToValidate Property

The property value is of type string, which is used to verify the programmatic ID of the input control that the control will evaluate. If this is an illegal ID, an exception is thrown.

· Display property

The property value is the ValidatorDisplay type, which is used for the display behavior of the specified validation control. This property can be one of the following values: (1) The none-validation control is never displayed inline. Use this option if you want the error message to be displayed only in the ValidationSummary control. (2) static-If the validation fails, the validation control displays an error message. Even if the input control passes validation, space is allocated for each error message in the Web page. The page layout does not change when the validation control displays its error message. Because the page layout is static, multiple validation controls for the same input control must occupy different physical locations on the page. (3) dynamic-If the validation fails, the validation control displays an error message. The space to dynamically allocate error information on the page when validation fails. This allows multiple validation controls to share the same physical location on the page. Note: The physical layout of the page changes because the validation control's space is dynamically created. To prevent page layouts from changing when a validation control becomes visible, you must resize the HTML element that contains the validation control so that it is large enough to hold the maximum size of the validation control.

· ErrorMessage Property

The property value is string, which is used to display the error message in the ValidationSummary control when validation fails. If the Text property of the validation control is not set, it is still displayed in the validation control when the validation fails. The ErrorMessage property is typically used to provide various messages for validation controls and ValidationSummary controls. Note: This property does not convert special characters to HTML entities. For example, the less-than character (<) is not converted to <. This allows HTML elements, such as elements, to be embedded in the value of this property

· IsValid Property

The property value is type bool, which indicates whether the input control specified by the ControlToValidate property is determined to be valid.

Validation controls that derive from this class do not have to implement the above common properties again, as long as additional attributes and validation logic are defined as required by the application. For example, for the RangeValidator control, in addition to the above common properties, the MinimumValue and MaximumValue properties that are used to qualify the range of values are defined, as well as the Type property of the data type that specifies the value to compare. In addition, the validation logic for the control is implemented by overriding the Basevalidator.evaluateisvalid method. In this view, BaseValidator simplifies the implementation of custom validation controls and facilitates control developers.

CustomValidator is derived from the BaseValidator class, which is one of 5 built-in validation controls. Typically, the page developer uses CustomValidator to add custom validation logic, as long as it is done by defining the event handling method for the ServerValidate event and the ClientValidationFunction property. Because CustomValidator does not provide a reuse mechanism (the Access property is public), a custom validation control cannot derive from the class.

(2) Client implementation mechanism

The 3 core objects that developers must master to implement validation controls are described above. Mastering the definition and use of these objects is important for developing validation controls. Through them, we can add validation logic to the server validation. When the page is returned, the input data for the validation target control is sent to the server side to participate in the validation logic. If the input data does not meet the validation criteria, the page is rendered again and the user is asked to enter again. The entire verification process may require multiple round-trip, which will inevitably reduce the ease of use of the application and add a burden to the server.

To address these issues, developers must learn to add a client-side validation mechanism for validation controls. If the user's browser supports DHTML and JavaScript technology, and the page and validation controls have EnableClientScript set to true, validation can be performed on the client. Client-side validation enhances the validation process by checking user input and changing some page effects before sending user input to the server. For example, by detecting input errors on the client side, the information required for server-side validation is prevented from passing back and forth. Server-side validation is always performed, which may seem like a duplication with client validation, not actually. For security reasons, if some users bypass client authentication by manually submitting malicious data, the execution of server-side validation will provide strong support for securing the application and even for the security of the server.

In asp.net 2.0, if a developer uses a built-in validation control to implement validation, ASP.net 2.0 automatically generates relevant JavaScript code. If the developer looks at the relevant HTML source code, some JavaScript file links from WebResource.axd will be found. However, we are unable to view the related file code. This is different from the ASP.net 1.x. In ASP.net 1.x, by default, a Webuivalidation.js file is included in the directory "C:\Inetpub\wwwroot\aspnet_client\system_web\ version number". The file includes JavaScript code that implements client-side validation. Developers can read the code to understand how validation functions are implemented. ASP.net 2.0 does not exist in the relevant source code files, but through WebResource.axd and other mechanisms to achieve.

The implementation of client-side validation is mainly concerned with knowledge of implementing client-side functionality. The content is explained in detail in the previous article. Interested readers can read about the article.

   3. Summary

This article mainly introduces the built-in validation controls, as well as the custom validation control implementation mechanism. In fact, if readers develop their own validation controls, they will find that the process requires a lot of knowledge. For example, server-side programming languages, JavaScript, CSS, DHTML, and so on. Therefore, if the reader wants to create a high quality validation control, it should not only understand the relevant knowledge, but must reach the level of proficiency.

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.