Ensure data integrity with validation in ASP.NET

ASP.NET provides numerous validation controls that make it easy to validate data entered via a Web Form. Here are various ways to validate user-entered data via these controls.

Data collection is an integral part of most applications whether Web- or Windows-based. It varies from obtaining user feedback to user profile information. This data is often stored in a backend database system, which contains data constraints defining what is and is not allowed, so the data collected and sent to the database system must adhere to the constraints to avoid errors.

Validation dos and don'ts

The many languages available for working with the .NET Framework make it easy to develop code that validates data entered by a user before sending it to a database table. In addition, ASP.NET provides numerous validation controls that make it easy to validate data entered via a Web Form.

Though your .NET development toolbox is well-stocked, these tools are useless if you use them ineffectively. Be aware of what type of data checks you need to perform to ensure data integrity. The following list outlines how you should approach data validation:

  • Required: One of the most basic validation methods is defining certain fields as required, so that users must enter something in the field before they can save the data. Likewise, database tables may contain required columns—passing null data to these columns will raise an exception.
  • Data type: Another obvious way to validate user input is checking the data type against what is expected. For example, a date field should only accept legal dates (although there are numerous format options). Trying to pass an invalid date value to a database date column will trigger an exception.
  • Length: The length of a date entry field is one of the most common validation errors that I encounter. You must adhere to the size limit defined in the database or data store to ensure an exception isn't raised. This is easy in both ASP.NET Web and Windows Forms by using a field's MaxLength property or attribute. You should also validate the data length in the code since Web Forms may be bypassed by passing data to the server via HTTP Server variables.
  • Format: A field's type can determine its proper format. A good example is a date field that may use the xx/xx/xxxx format. Likewise, telephone number and salary fields utilize specific formats. You may create a custom field control, utilize JavaScript in ASP.NET, or apply formatting via code and the String.Format method or using regular expressions to apply necessary formatting to user data. This may be part of data validation, and the validation shouldn't accept improperly formatted data.
  • Range of values: Utilizing a range of values as a guide for data entry allows you to easily check if an entered value falls within it. This type of check may be used for entering salaries, zip codes, and so forth.
  • Check against another field value: You may validate a field's value against another field on the form. The second field could be hidden or entered by the user. One common example is date entries where a user may enter start and end dates, and the end date should always be greater than or equal to the start date.

Putting this list in action depends on the application type. We'll examine an example using the ASP.NET platform. The sample Web Form has four fields:

  • Username: Required text field limited to 50 characters. A RequiredFieldValidator control is used to ensure a value is entered.
  • Zip code: Text field accepting a five character zip code in the integer range of 00000 and 99999. It's not required, so validation is performed only if a value is entered. A RegularExpressionValidator control is used to ensure only five numeric digits are entered. A RangeValidator control verifies the value is in the legal range.
  • Start date: Text field accepting a date value. A RequiredFieldValidator control is used to make sure a value is entered. A CompareValidator control is used to ensure only a date type of date is entered, and another CompareValidator control is used to verify the start date is less than the end date.
  • End date: Text field accepting a date value. A RequiredFieldValidator control is used to make sure a value is entered. A CompareValidator control is used to make sure a date is entered in the field, and another CompareValidator control verifies the end date is greater than the start date.

The complete Web Form source is listed next. It includes all fields and validation controls with a JavaScript button for submitting the form, thus triggering the validation:

<%@ Page language="c#" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<title>Builder.com Data Validation Example</title>
<body text="#000000" bgColor="#ffffff">
<form id="frmDataValidation" method="post" runat="server">
<h1>Builder.com Data Validation Example</h1>
<asp:textbox id="userName" Runat="server" MaxLength="50">
<asp:requiredfieldvalidator id="userNameRequiredFieldValidator" runat="server"
ErrorMessage="Please enter a username." EnableClientScript="False"
<br />
Zip code:
<asp:textbox id="zip" Runat="server" MaxLength="5" Columns="7">
<asp:regularexpressionvalidator id="zipRegExValidator" Runat="server"
ErrorMessage="Please enter a valid zip code (00000 - 99999)."    
EnableClientScript="False" ControlToValidate="zip" ValidationExpression="^\d{5}$">
<asp:RangeValidator id="rvZipCode" runat="server" ControlToValidate="zip"
ErrorMessage="Please enter a valid zip code (00000 - 99999)."
MaximumValue="99999" MinimumValue="00000" Type="Integer" Visible="False">
<br />
Start date:
<asp:TextBox ID="txtStartDate" Runat="server" Width="75"
<asp:RequiredFieldValidator ControlToValidate="txtStartDate"
Runat="server" ErrorMessage="Please enter a valid start date(mm/dd/yyyy)."
<asp:CompareValidator id="cvStartDate" runat="server" ControlToValidate="txtStartDate"
Operator="DataTypeCheck" Type="Date" ErrorMessage="Please enter a valid start
mm/dd/yyyy)." EnableClientScript="False">
<asp:CompareValidator id="cvStartDateLessThanEndDate" runat="server"
ErrorMessage="Start date must be less than end date."
Type="Date" Operator="LessThanEqual" ControlToCompare="txtEndDate"
<br />
End date:
<asp:TextBox ID="txtEndDate" Runat="server" Width="75" AutoPostBack="True"
<asp:RequiredFieldValidator ControlToValidate="txtEndDate"
Runat="server" ErrorMessage="Please enter a valid end date (mm/dd/yyyy)."
<asp:comparevalidator id="cvEndDate" runat="server"
Operator="DataTypeCheck"    Type="Date" ErrorMessage="Please enter a valid end
(mm/dd/yyyy)." EnableClientScript="False" Display="Dynamic">
<br />
<input type="button" value="Submit" id="submitButton"
onclick="document.forms[0].submit();" />

This simple example demonstrates the various ways to validate data entered by a user via ASP.NET validation controls.

Check the data

Ensuring data integrity is important to proper application operation. User input should be properly validated to avoid application errors when the data is saved to a data source like a SQL Server database. One approach to application development preaches building test cases first before actual coding. This is a good technique for a user interface as well; it helps the developer recognize data validation opportunities.

TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!