How to: Create a Custom Validation Rule

You can create your own validation rules. To do this, you derive your own rule class from a validation rule class. Validation rules derive from the ValidationRule base class.

Visual Studio Team System Test Edition provides some predefined validation rules. For more information, see About Validation Rules.

Note

You can also create custom extraction rules. For more information, see About Extraction Rules.

To create custom validation rules

  1. Open a Test Project that contains a Web test.

  2. (Optional) Create a separate Class library project in which to store your validation rule.

    Important noteImportant Note:

    You can create the class in the same project that your tests are in. However, if you want to reuse the rule, it is better to create a separate Class library project in which to store your rule. If you create a separate project, you must complete the optional steps in this procedure.

  3. (Optional) In the Class library project, add a reference to the Microsoft.VisualStudio.QualityTools.WebTestFramework DLL.

  4. Create a class that derives from the ValidationRule class. Implement the Validate and RuleName members.

  5. (Optional) Build the new Class library project.

  6. (Optional) In the Test Project, add a reference to the Class library project that contains the custom validation rule.

  7. In the Test Project, open a Web test in the Web Test Editor.

  8. To add the custom validation rule to a Web test request, right-click a request and select Add Validation Rule.

    The Add Validation Rule dialog box appears. You will see your custom validation rule in the Select a rule list, together with the predefined validation rules. Select your custom validation rule and then click OK.

  9. Run your Web test.

Example

The following code shows an implementation of a custom validation rule. This validation rule mimics the behavior of the predefined Required Tag validation rule. Use this example as a starting point for your own custom validation rules.

using System;
using System.Diagnostics;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace SampleWebTestRules
{
    //-------------------------------------------------------------------------
    // This class creates a custom validation rule named "Custom Validate Tag"
    // The custom validation rule is used to check that an HTML tag with a 
    // particular name is found one or more times in the HTML response.
    // The user of the rule can specify the HTML tag to look for, and the 
    // number of times that it must appear in the response.
    //-------------------------------------------------------------------------
    public class CustomValidateTag : ValidationRule
    {
        /// Specify a name for use in the user interface using the
        /// System.ComponentModel.DisplayName attribute.
        /// The user sees this name in the Add Validation dialog box.
        [System.ComponentModel.DisplayName("My Validation Rule")]

        /// Specify a description for use in the user interface using the
        /// System.ComponentModel.Description attribute.
        /// The user sees this description in the Add Validation dialog box.
        [System.ComponentModel.Description("A Description of My Rule")]

        // The name of the required tag
        private string RequiredTagNameValue;
        public string RequiredTagName
        {
            get { return RequiredTagNameValue; }
            set { RequiredTagNameValue = value; }
        }

        // The minimum number of times the tag must appear in the response
        private int MinOccurrencesValue;
        public int MinOccurrences
        {
            get { return MinOccurrencesValue; }
            set { MinOccurrencesValue = value; }
        }

        // Validate is called with the test case Context and the request context.
        // These allow the rule to examine both the request and the response.
        //---------------------------------------------------------------------
        public override void Validate(object sender, ValidationEventArgs e)
        {
            bool validated = false;
            int numTagsFound = 0;

            foreach (HtmlTag tag in e.Response.HtmlDocument.GetFilteredHtmlTags(RequiredTagName))
            {
                Debug.Assert(string.Equals(tag.Name, RequiredTagName, StringComparison.InvariantCultureIgnoreCase));

                if (++numTagsFound >= MinOccurrences)
                {
                    validated = true;
                    break;
                }
            }

            e.IsValid = validated;

            // If the validation fails, set the error text that the user sees
            if (!validated)
            {
                if (numTagsFound > 0)
                {
                    e.Message = String.Format("Only found {0} occurences of the tag", numTagsFound);
                }
                else
                {
                    e.Message = String.Format("Did not find any occurences of tag '{0}'", RequiredTagName);
                }
            }
        }
    }
}
Imports System
Imports System.Diagnostics
Imports System.Globalization
Imports Microsoft.VisualStudio.TestTools.WebTesting

Namespace SampleWebTestRules

    '-------------------------------------------------------------------------
    ' This class creates a custom validation rule named "Custom Validate Tag"
    ' The custom validation rule is used to check that an HTML tag with a 
    ' particular name is found one or more times in the HTML response.
    ' The user of the rule can specify the HTML tag to look for, and the 
    ' number of times that it must appear in the response.
    '-------------------------------------------------------------------------
    Public Class CustomValidateTag
        Inherits Microsoft.VisualStudio.TestTools.WebTesting.ValidationRule

        ' Specify a name for use in the user interface using the 
        ' System.ComponentModel.DisplayName attribute.
        ' The user sees this name in the Add Validation dialog box.
        <System.ComponentModel.DisplayName("My Validation Rule")>

        ' Specify a description for use in the user interface using the.
        ' System.ComponentModel.Description attribute.
        ' The user sees this description in the Add Validation dialog box.
        <System.ComponentModel.Description("A Description of My Rule")>

        ' The name of the required tag
        Private RequiredTagNameValue As String
        Public Property RequiredTagName() As String
            Get
                Return RequiredTagNameValue
            End Get
            Set(ByVal value As String)
                RequiredTagNameValue = value
            End Set
        End Property

        ' The minimum number of times the tag must appear in the response
        Private MinOccurrencesValue As Integer
        Public Property MinOccurrences() As Integer
            Get
                Return MinOccurrencesValue
            End Get
            Set(ByVal value As Integer)
                MinOccurrencesValue = value
            End Set
        End Property

        ' Validate is called with the test case Context and the request context.
        ' These allow the rule to examine both the request and the response.
        '---------------------------------------------------------------------
        Public Overrides Sub Validate(ByVal sender As Object, ByVal e As ValidationEventArgs)

            Dim validated As Boolean = False
            Dim numTagsFound As Integer = 0

            For Each tag As HtmlTag In e.Response.HtmlDocument.GetFilteredHtmlTags(RequiredTagName)

                Debug.Assert(String.Equals(tag.Name, RequiredTagName, StringComparison.InvariantCultureIgnoreCase))

                numTagsFound += 1
                If numTagsFound >= MinOccurrences Then

                    validated = True
                    Exit For
                End If
            Next

            e.IsValid = validated

            ' If the validation fails, set the error text that the user sees
            If Not (validated) Then
                If numTagsFound > 0 Then
                    e.Message = String.Format("Only found {0} occurences of the tag", numTagsFound)
                Else
                    e.Message = String.Format("Did not find any occurences of tag '{0}'", RequiredTagName)
                End If
            End If
        End Sub
    End Class
End Namespace

See Also

Tasks

How to: Add a Validation Rule to a Web Test

Walkthrough: Adding Validation and Extraction Rules to a Web Test

How to: Create a Custom Extraction Rule

Reference

ValidationRule

Microsoft.VisualStudio.TestTools.WebTesting.Rules

ValidateFormField

ValidationRuleFindText

ValidationRuleRequestTime

ValidationRuleRequiredAttributeValue

ValidationRuleRequiredTag

Change History

Date

History

Reason

June 2010

Changed sample code to use attributes included in Visual Studio 2008 for DisplayName and Description instead of method overrides that were used in previous versions.

Customer feedback.