Validation Controls - ASP.NET

{outline||<1> - |.<1> - }

See also the Validation Controls in the Class Library.

Common Properties

I have found that the ASP.NET validation controls work best with the following property settings.

IMPORTANT: To enable client-side validation, not only must you set EnableClientScript to "true", the Display property must be specified and cannot be "None".

runat="server" Display="Dynamic" Text="*" EnableClientScript="true" 
SetFocusOnError="true" ValidationGroup="MainValidationGroup"

User Feedback

User feedback can be accomplished in any combination of the following three ways.


<asp:ValidationSummary runat="server" ID="uxValidationSummary"
    ValidationGroup="MainValidationGroup" 
    EnableClientScript="true" 
    HeaderText="<b>Couldn't process your request for the following reason(s).</b>"  
    ShowMessageBox="false"  
    ShowSummary="true"  
    DisplayMode="BulletList"  
    BackColor="#ffff99" 
    BorderColor="Red"  
    BorderWidth="2px"  
    Font-Bold="false" 
    />


<asp:RequiredFieldValidator runat="server"  
    ControlToValidate="uxStartDateTextBox"  
    Display="Dynamic" 
    EnableClientScript="true"  
    SetFocusOnError="true"  
    Text=""  
    ValidationGroup="MainValidationGroup"  
    ID="uxStartDateRequiredValidator"  
    ErrorMessage="Start Date must be specified." >

    <asp:Image runat="server" ImageUrl="~/images/Exclamation.PNG" />
    
    </asp:RequiredFieldValidator>


Types of Validation

Required Field

With text

<asp:RequiredFieldValidator runat="server" Display="Dynamic" EnableClientScript="true" 
    SetFocusOnError="true" Text="*" ValidationGroup="MainValidationGroup"
    ControlToValidate="uxStartDateTextBox"  
    ID="uxStartDateRequiredValidator" 
    ErrorMessage="Start Date is required." 
    />

With an image

<asp:RequiredFieldValidator runat="server" Display="Dynamic" EnableClientScript="true" 
    SetFocusOnError="true" ValidationGroup="MainValidationGroup"
    ControlToValidate="uxStartDateTextBox"  
    ID="uxStartDateRequiredValidator" 
    ErrorMessage="Start Date is required." 
    >
    
    <asp:Image ID="Image9" runat="server" ImageUrl="~/images/Exclamation.PNG" />
    
    </asp:RequiredFieldValidator>

Data Type

With text

<asp:CompareValidator runat="server" Display="Dynamic" EnableClientScript="true"
    SetFocusOnError="true" Text="*" ValidationGroup="MainValidationGroup"  
    ID="uxStartDateDataTypeValidator" 
    ControlToValidate="uxFromDateTextBox"
    Operator="DataTypeCheck" 
    Type="Date" 
    ErrorMessage="Start Date must be a valid date." 
    >


With an image

<asp:CompareValidator runat="server" Display="Dynamic" EnableClientScript="true"
    SetFocusOnError="true" ValidationGroup="MainValidationGroup"  
    ID="uxStartDateDataTypeValidator" 
    ControlToValidate="uxFromDateTextBox"
    Operator="DataTypeCheck" 
    Type="Date" 
    ErrorMessage="Start Date must be a valid date." 
    >
    
    <asp:Image ID="Image9" runat="server" ImageUrl="~/images/Exclamation.PNG" />
    
    </asp:CompareValidator>

Range Validation

Note that the this type of validation also checks the data type, rendering the data type validation (above) redundant.

With text

<asp:RangeValidator runat="server" Display="Dynamic" Text="" EnableClientScript="true" 
    SetFocusOnError="true" ValidationGroup="MainValidationGroup" 
    ID="uxPhoneNbrRangeValidator" 
    ErrorMessage="Phone Number must be a ten-digit number, with no punctuation." 
    ControlToValidate="uxPhoneNbrTextBox"
    MinimumValue="1000000000" MaximumValue="9999999999" 
    Type="Double"                                 
    >

With an image

<asp:RangeValidator runat="server" Display="Dynamic" Text="" EnableClientScript="true" 
    SetFocusOnError="true" ValidationGroup="MainValidationGroup" 
    ID="uxPhoneNbrRangeValidator" 
    ErrorMessage="Phone Number must be a ten-digit number, with no punctuation." 
    ControlToValidate="uxPhoneNbrTextBox"
    MinimumValue="1000000000" MaximumValue="9999999999" 
    Type="Double"                                 
    >
    
    <asp:Image ID="Image9" runat="server" ImageUrl="~/images/Exclamation.PNG" />
    
    </asp:RangeValidator>

Comparison to Another Field

With text

<asp:CompareValidator runat="server" Display="Dynamic" Text="*" EnableClientScript="true" 
    SetFocusOnError="true" ValidationGroup="MainValidationGroup" 
    ID="uxEndDateRangeValidator" 
    ControlToValidate="uxEndDateTextBox"
    Operator="GreaterThanEqual" 
    ControlToCompare="uxStartDateTextBox" 
    Type="Date"
    ErrorMessage="End Date must be on or after the Start Date." 
    />

With an image

<asp:CompareValidator runat="server" Display="Dynamic"
    EnableClientScript="true" 
    SetFocusOnError="true" ValidationGroup="MainValidationGroup" 
    ID="uxEndDateRangeValidator" 
    ControlToValidate="uxEndDateTextBox"
    Operator="GreaterThanEqual" 
    ControlToCompare="uxStartDateTextBox" 
    Type="Date"
    ErrorMessage="End Date must be on or after the Start Date." 
    >
    
    <asp:Image ID="Image9" runat="server" ImageUrl="~/images/Exclamation.PNG" />
    
    </asp:CompareValidator>

Custom Validation

The asp:CustomValidator works best when it is used with client-side validation. Custom validation is shown in the following sample code.

ASPX Code (with text)

<asp:CustomValidator runat="server" Display="Dynamic" Text="" 
    SetFocusOnError="true" ValidationGroup="MainValidationGroup" EnableClientScript="true"
    ClientValidationFunction="validateCheckBoxes"
    ErrorMessage="At least one option must be selected."
    ID="uxCheckBoxesValidator"
    ValidateEmptyText="true"
    OnServerValidate="uxCheckboxes_Validate"
    Text="*"
    />

ASPX Code (with an image)

<asp:CustomValidator runat="server" Display="Dynamic" Text="" 
    SetFocusOnError="true" ValidationGroup="MainValidationGroup" EnableClientScript="true"
    ClientValidationFunction="validateCheckBoxes"
    ErrorMessage="At least one option must be selected."
    ID="uxCheckBoxesValidator"
    ValidateEmptyText="true"
    OnServerValidate="uxCheckboxes_Validate"
    >
    
    <asp:Image ID="Image9" runat="server" ImageUrl="~/images/Exclamation.PNG" />
    
    </asp:CustomValidator>

Server Code

This code is referenced via the OnServerValidate property of the asp:CustomValidator control, and must have the signature indicated.

Protected Sub uxCheckBoxes_Validate(ByVal source As Object, ByVal args As ServerValidateEventArgs) _
Handles uxCheckBoxesValidator1.ServerValidate, uxCheckBoxesValidator2.ServerValidate

    Dim checkBoxes() As CheckBox = New CheckBox() {uxCheckBox1, uxCheckBox2, uxCheckBox3, _
            uxCheckBox4, uxCheckBox5, uxCheckBox6, uxCheckBox7, uxCheckBox8 }

    Dim somethingChecked As Boolean = False

    For i As Integer = 0 To checkBoxes.GetUpperBound(0)
        If checkBoxes(i).Checked Then
            somethingChecked = True
            Exit For
        End If
    Next

    args.IsValid = somethingChecked

End Sub

Client Code

This code is referenced via the ClientValidationFunction property of the asp:CustomValidator control, and requires that the EnableClientScript property be set to True. The function must have the signature indicated. The arguments are the same as for the server-side function.

function validateCheckBoxes(sender, e)
{
    var selectedCheckBoxes;
    selectedCheckBoxes = 0;
    
    for (i = 0; i < document.forms[0].elements.length; i++) 
        if (document.forms[0].elements[i].type == "checkbox")
            if (document.forms[0].elements[i].checked)
                selectedCheckBoxes;

    e.IsValid = (selectedCheckBoxes > 0);
}

Validating User Controls

NOTE: Although a number of ASP.NET forums recommend the following solution to validating user controls, I've found that using a CustomValidator is more straightforward.

In order to specify a custom user control for the ControlToValidate property of any of the validation controls, you must apply the ValidationProperty attribute to your user control class. This attribute specifies the property to use when validating the control.

<ValidationProperty("ItemsChecked")> _
Partial Class UserControls_CheckedListBox
...

End Class