Validating Input Data
Most ASP.NET pages are made of controls. More often than not, pages are built just dropping controls onto the Visual Studio 2005 designer without much additional work of configuration. So what kind of stuff should you be adding then? The quick answer is: anything that can limit the user's freedom in typing fuzzy characters. For example, a text box control should have a maximum length and, more importantly, this parameter must be checked before using the typed text.
Likewise, if a text box has to return data of a given known type (number, date), you should ensure that valid and legitimate data comes out of the text box in all cases.
Strings representing special data such as an e-mail address, a Social Security number (SSN), a phone number, and strings must be parsed and verified before use. In all cases, potentially dangerous and unnecessary characters should be stripped off. Always.
If you have to be serious about security (let's say itnot all applications need the same level of security), you should be harsh and define strict rules even at the cost of annoying users. For example, a valid and significant e-mail address can be written with only letters, digits, and a few punctuation marks. Why enable users to type more than just this?
Event and request validation, viewstate protection barriers, and validation controls are all framework tools that form a first line of defense against possible attacks. You should never rely on them alone. If it helps you, write your code as if they were not there. I don't usually suggest disabling built-in features, but if you're going to take security seriously and replace them with your own layer, it may be acceptable.
Whatever set of automatic barriers you use, it's you and only you who is ultimately responsible for the data your code parses and processes. A back-end validation layer is an absolute necessity. You typically place it on top of the business layer where you prepare your entities with input data and safe default values.
ASP.NET Validation Controls
ASP.NET provides a fair number of validation controls to help you check input data before data is posted and processed on the server. Validation controls provide an easy-to-use mechanism to perform a variety of validation tasks, including testing for valid types, values within a given range, or required fields. Each validation control references an input control located somewhere in the ASP.NET page.
A validator may have a client- and server-side engine to process input data. When the page is ready for submission, the current contents of the monitored control is passed to the validator for further processing. If the validator has a client-side engine, the post won't happen until the validator says it's all right. If there's no client-side engine active, the page posts back but no postback event is ever fired if the input doesn't match expectations.
Each validator performs a different type of verification. Table 2 shows the types of validation controls supported by ASP.NET 2.0.
Table 2: ASP.NET Validation Controls.
||Compares the contents of the control against a fixed value or the value of another control in the same page. The comparison is made by using an operator such as LessThan, Equal, or GreaterThan.
||You use this validator when you need to employ custom logic to validate the input.
||Ensures that the input falls within a given range of values. The interval can be expressed in terms of numbers, strings, or dates.
||Ensures that the input value matches the pattern defined by a regular expression.
||Ensures that the user doesn't leave the field blank.
You can apply multiple validation controls to an input control in order to validate it according to a variety of different criteria. For example, you can apply two validators to a text box to make sure that the user doesn't leave it empty and that its content matches the typical format of a Social Security number. In this case, you use a RequiredFieldValidator combined with a RegularExpressionValidator.
All validators inherit from a common base BaseValidator class, which in turn inherits from Label. Table 3 lists the properties shared by all validator controls. Listing 1
shows some validators in action in a sample page.
Table 3: ASP.NET Validation Control Properties.
||String property, indicates the input control to validate. The control is identified by name.
||Ignored in case of server-side validation, indicates how the space for the error message should be allocated-either statically or dynamically. The default is Dynamic. If Static, the browser will reserve space for the message but leave it blank.
||Indicates whether client-side validation is enabled for the control.
||Indicates whether the validator is enabled.
||Specifies the text for the error message.
||Indicates the color of the message displayed when validation fails. Red by default.
||Indicates whether the contents of the monitored input control is coherent with validation rules.
||Indicates whether the focus should be automatically moved to the control where validation failed.
||Specifies the text that is sometimes displayed in lieu of the error message. Note, though, this text does not replace the contents of ErrorMessage in the summary text.
||Indicates the validation group to which the validator belongs.
All validators inject some script code in the client page if client script support is enabled for the validator's EnableClientScript
In Table 3 you see two similar looking propertiesErrorMessage and Text. What's the purpose of each?
property sets the official message that each validation control displays in case it detects an error. If the Text
property is also set, it would take precedence over ErrorMessage
. However, the goal of Text
is slightly different.
property is designed to display an inline message exactly where the validator is located. Instead, the ErrorMessage
property is designed to display in the validation summary. What's the validation summary then?
The ValidationSummary control is a label that displays a summary of all validation errors occurring on a Web page. The summary collects error messages from all validators in the page and displays them according to the selected display mode: list, bulleted list, or plain text. Whatever the format is, the summary can be displayed as text in the page or in a pop-up message box. Note that the output of the ValidationSummary control is not displayed until the page posts back. Here's an example:
HeaderText="The following errors occurred:"
It should be noted that error messages are displayed as HTML, so they can contain any HTML formatting attribute.
By default, validation occurs in an all-or-nothing kind of way. This means, for example, that if you have two groups of input fields and two submit buttons, clicking either button will always validate all controls in both groups. You have to explicitly define custom validation groups if you want to validate some controls when one button is clicked and some others when the other button is clicked. You use the ValidationGroup
property to define custom validation groups. Here's an example:
<asp:TextBox runat="server" id="TextBox3" />
ErrorMessage="TextBox1 is mandatory" />
<asp:TextBox runat="server" id="TextBox4" />
ErrorMessage="TextBox2 is mandatory" />
<asp:Button ID="Button1" runat="server"
<asp:Button ID="Button2" runat="server"
In the code snippet, you find two validators each belonging to a distinct group: Group1 and Group2. The code snippet also contains two buttons each with the ValidationGroup
property set. Guess what happens?
Quite simply, a button click validates all and only the controls belonging to the same validation group. In this way, you can make the validation process as granular as needed. Note that validation groups are not a supported feature in ASP.NET 1.x.