Perform HTML form validation with ASP.NET

ASP.NET's validation mechanism gives even amateurs the ability to validate data through a structured approach. Learn about ASP.NET's validators and discover how you can incorporate them in your pages.

One of the many strengths of ASP.NET is that it provides a framework for common Web applications through structured interfacing. Most business applications involve data input, validation, and some form of output. Web applications are no different.

HTML forms are created for users to enter data; however, data validation can occur through some combination of client-side scripts or server-side validation. The drawback to this is that putting that responsibility on an unknown client tool, the browser, can produce less than exemplary results.

Therefore, data should be validated on the server where you have full control of the outcome. This used to be handled by parsing individual request elements and running them through a validation mechanism. Without much direction, this validation mechanism can run amuck. However, ASP.NET's validation mechanism gives even amateurs the ability to validate data through a structured approach. This is done through validators. In this article, I'll describe ASP.NET's validators and explain how you can incorporate them in your pages.

There are five validators for user input: RequiredFieldValidator, RegularExpressionValidator, CompareValidator, RangeValidator, and CustomValidator.

  • RequiredFieldValidator checks to see if data was entered or selected for the input control.
  • RegularExpressionValidator uses a regular expression to validate the value of the input control.
  • CompareValidator checks the input control's value against a fixed value or another input control's value.
  • RangeValidator checks to ensure that the value of an input control is between two fixed values.
  • CustomValidator uses a custom routine to validate the input.

It's simple to use these validators in your page. Simply add one or more validator for each corresponding form element whose input you want to validate. You can also add output text to each validator that will display when an invalid condition has occurred. Once all the data has been validated against the validators, any invalid conditions can be reported back through the ValidationSummary control. This is a simple developer-defined list of invalid conditions. Here's the code that will accomplish all this:

<title>Validator Example</title>
<form runat="server">
<asp:ValidationSummary runat="server"
    HeaderText="Validation summary:"/>
<asp:RequiredFieldValidator runat="server"
    ErrorMessage="The value is required.">*
<asp:RegularExpressionValidator runat="server"
    ErrorMessage="The value must be 2 digits."
<asp:CompareValidator runat="server"
    ErrorMessage="The value does not match the other value."
<asp:RangeValidator runat="server"
    ErrorMessage="The value is not between 10 and 20."
<asp:CustomValidator runat="server" id="CustomValidator1"
    ErrorMessage="13 is a very unlucky number; pick another one."
Enter a 2-digit value between 10 and 20: <input type="text" runat="server"
 id="txtTest" size="6">
Value will be compared to: <input type="text" runat="server" id="txtCompare"
size="6" value="10">
<input type="submit" id="cmdSubmit" runat="server" value="OK">

And on your code-behind within your page class, add these two methods:

private void cmdSubmit_ServerClick(object sender, System.EventArgs e)
    if (Page.IsValid)
        //Do next necessary steps.

private void CustomValidator1_ServerValidate(object source,
System.Web.UI.WebControls.ServerValidateEventArgs args)
    args.IsValid = Convert.ToInt32(args.Value) != 13;

JavaScript is automatically created for you for client-side validation before submission. However, the final test for validity is done on the server. During the cmdSubmit_ServerClick() event, the IsValid property of the Page instance is checked. If all the validators pass their tests, then the Page is marked as valid and the event is carried out. In this case, "Success!" is simply written to the Response buffer and the Response is ended.

For each validator, a red asterisk will be placed beside the input if the value does not satisfy the validation attempt. Each validator's error message will be displayed in the ValidationSummary area. The CustomValidator is a bit different. If all the other validation attempts are successful, then the CustomValidator1_ServerValidate() event occurs. The input control's value is then checked to see if it equals 13. If so, the IsValid property is set to false. In order to test this event on this example, you need to set the compare text's value to 13; otherwise, the CompareValidator will exit and the _ServerValidate() event will not occur.

With a little crafty coding, a more complex validation mechanism can be constructed using ASP.NET's validators as a foundation. For more information on these validators, visit the MSDN Web site.

Keep your developer skills sharp by automatically signing up for TechRepublic's free Web Development Zone newsletter, delivered each Tuesday.

Editor's Picks

Free Newsletters, In your Inbox