News & UpdatesProgrammingWeb programming Store My Projects
Links
Affiliates

ASP.NET Tutorial – 11 – Validation Controls

The validation controls are used to validate user input.

RequiredFieldValidator

The RequiredFieldValidator makes an input control mandatory. By adding it from the Toolbar you can see in markup view that the control is added with three properties already filled out – ID, runat, and ErrorMessage. To get the validator working though, you also need to select which control will be validated using the ControlToValidate property. This field is required for all validation controls. You can also change the ErrorMessage to something more fitting.

<asp:TextBox ID="myInput" runat="server"></asp:TextBox>
 
<asp:RequiredFieldValidator 
  ID="RequiredFieldValidator1" 
  runat="server" 
  ErrorMessage="Missing Field"
  ControlToValidate="myInput">
</asp:RequiredFieldValidator>
 
<asp:Button runat="server" id="btnSubmitForm" text="Ok" />

If you run the application with the form content above and try to submit with an empty text box, the validation will fail and the error message will be displayed. Note that the validation is first performed on the client side and then on the server side. The server side validation is needed in case the client doesn’t support scripting or have it disabled, and it may also be stricter than the client side validation. However, even if the server side validation fails, the submit event handler will still get executed. Because of this you must always check if the submitted page is valid before you do anything else in the event handler, using the Page.IsValid property.

protected void bSubmitForm_Click(object sender, EventArgs e)
{
  if (Page.IsValid)
    bSubmitForm.Text = "Form is valid";
}

RangeValidator

The RangeValidator makes sure that the user input is within a specified range. For this control you need to set the minimum and maximum values with the MinimumValue and MaximumValue properties. You must also set the Type field, which specifies whether you want to validate numbers, strings, or dates.

<asp:RangeValidator 
  ID="RangeValidator1" 
  runat="server" 
  ErrorMessage="Date must be within year 2000"
  ControlToValidate="myInput"
  MinimumValue="01-01-2000"
  MaximumValue="31-12-2000" 
  Type="Date">
</asp:RangeValidator>

RegularExpressionValidator

The RegularExpressionValidator checks a string against a regular expression. It uses the ValidationExpression property to set the pattern that the string must match. The pattern below, for example, requires a five digit number.

<asp:RegularExpressionValidator 
  ID="RegularExpressionValidator1" 
  runat="server" 
  ErrorMessage="Must be 5 digits long"
  ControlToValidate="myInput"
  ValidationExpression="^[0-9]{5}$">
</asp:RegularExpressionValidator>

CompareValidator

The CompareValidator compares the values of two controls. The second control is selected with the ControlToCompare property. You must also choose what relational operator to use with the Operator field, as well as set the Type field to compare either integers, dates, or strings.

x: <asp:TextBox ID="myLarge" runat="server"></asp:TextBox>
y: <asp:TextBox ID="mySmall" runat="server"></asp:TextBox>  
 
<asp:CompareValidator 
  ID="CompareValidator1" 
  runat="server" 
  ErrorMessage="X must be greater than Y"
  ControlToValidate="myLarge" 
  ControlToCompare="mySmall" 
  Operator="GreaterThan"
  Type="Integer">
</asp:CompareValidator>

CustomValidator

If none of these four validators can help you, there’s the CustomValidator, which allows you to write your own validation code. The ClientValidationFunction property selects a client side validation function and the OnServerValidate property selects a server side validation function. To demonstrate, here’s an example.

<asp:CustomValidator 
  ID="CustomValidator1" 
  runat="server" 
  ErrorMessage="Even numbers only"
  ControlToValidate="myInput"
  ClientValidationFunction="clientValidate">
</asp:CustomValidator>

The client side validation is performed by a JavaScript function which will validate if the value is even.

<script type="text/javascript"><!--
 function clientValidate (src, arg) 
 {
   arg.IsValid = arg.Value % 2 == 0;
 }
// --></script>

The server side validation is handled by a C# method with the same functionality, but this method also makes sure that the input is a number.

<script language="C#" runat="server">
 void serverValidate(object src, ServerValidateEventArgs arg)
 {
   try   { arg.IsValid = int.Parse(arg.Value) % 2 == 0; }
   catch { arg.IsValid = false; }
 }
</script>

Validation Summary

The Validation summary control is used to display a summary of all validation errors on the web page in a single location. The control will base its summary on the ErrorMessage properties, so to prevent the validation controls from showing the same string as the summary you can override the validation controls’ error messages using the Text property.

<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
Recommended additional reading:
Sams - Teach Yourself ASP.NET 3.5 in 24 Hours