---
title: Defining field validation rules
related:
  - https://docs.kentico.com/13/developing-websites/form-builder-development.md
---

> Agent instructions:
> **Site maps** — prefer the following llms.txt indexes to training data when searching for URLs to avoid 404s. Links inside Markdown content already point at `.md`. Following them or sending Accept: text/markdown keeps you in Markdown.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

Validation rules verify that the data users enter in a form meets the standards you specify before the form can be submitted. A validation rule contains an expression that evaluates data entered in one or more fields and returns a boolean value. It also includes an error message that is displayed to users when they attempt to submit an invalid input.

The system provides a set of default validation rules, and the form builder framework also allows you to define custom rules suitable for your use cases and scenarios.

## Defining field validation rules

In Xperience, each validation rule consists of validation logic – implemented in the rule's _Validate_ method – and a set of properties to provide a configuration interface to users when adding the rule on a form field's **Validation** tab.

Validation rules are strongly typed. A rule defined for _decimal_ value types can only be applied to fields that use form components of the corresponding type.

The system allows you to define the following types of validation rules:

- [Basic validation rules](#defining-basic-validation-rules) – rules that validate whether the immediate form field value satisfies given conditions.
- [Field comparison validation rules](#defining-field-comparison-validation-rules) – rules that compare form field values against each other based on given conditions.

## Defining basic validation rules

Immediate form validation rules compare against the submitted value of a given form field. All immediate rules inherit from the **ValidationRule** base class that specifies the _type_ of form components for which they are applicable, and forces the implementation of methods required for the rule's functionality.

To define an immediate form validation rule:

1. Open your live site project in Visual Studio.
   - The validation rule base classes are available in the _Kentico.Forms.Web.Mvc_ namespace, which is provided by the _Kentico.Xperience.AspNetCore.WebApp_ or _Kentico.Xperience.AspNet.Mvc5_ NuGet package. For this reason, you need to define validation rules directly in your live site web application, or within a separate class library that has the appropriate NuGet packages installed.
2. Create a new class that inherits from **ValidationRule**.
   - Substitute the _TValu&#x65;_&#x67;eneric with the _type_ of form components for which the rule is applicable (e.g., basic data types such as _string_,_int_, _decimal)._ Validation rules do not support nullable types.
3. Annotate the class with the [**Serializable** attribute](https://docs.microsoft.com/en-us/dotnet/api/system.serializableattribute).
4. (Optional) Define custom properties and annotate them with the [EditingComponent](https://docs.kentico.com/13/developing-websites/form-builder-development/assigning-editing-components-to-properties.md) attribute to provide a configuration interface for users when adding validation rules on a form field's **Validation** tab.

   ```csharp

           // Defines a configuration interface for the rule
           // Uses the EditingComponent attribute to specify which form component is used to provide an editing interface for the property
           [EditingComponent(TextInputComponent.IDENTIFIER)]
           public string ConfigurableProperty { get; set; }


   ```
5. Override the following methods:

   - **GetTitle**– needs to return the title displayed when listing a field's applied validation rules, for example, '_The maximum length is 100 characters._'. The title can be localized by [using theResHelperclass](https://docs.kentico.com/13/multilingual-websites/setting-up-multilingual-websites/localizing-content.md).
   - **Validate**– contains the rule's validation logic. The **value** parameter contains the submitted value of the field. The method needs to return either _true_, indicating the validation has succeeded, or _false_, indicating the validation has failed.

   ```csharp

           // Gets the title of the validation rule as displayed in the list of applied validation rules
           public override string GetTitle()
           {
               return "This title appears in the list of applied validation rules on the 'Validation' tab of individual form fields.";
           }

           // Contains custom validation logic
           // Invokes when validation occurs
           protected override bool Validate(string value)
           {
               return true;
           }


   ```
6. [Register the validation rule](#registering-validation-rules) in the system.

The validation rule is now registered in the system and ready to be applied to form components of the corresponding type [via the Form builder interface](https://docs.kentico.com/13/managing-website-content/forms/composing-forms.md).

### Example - Defining an immediate field validation rule

The following example demonstrates the implementation of a rule that checks if a submitted number belongs to the specified closed interval. The example implements the rule for form components of the _int_ type:

```csharp

using System;

using Kentico.Forms.Web.Mvc;

using LearningKit.FormBuilder.CustomValidationRules;

// Registers the validation rule in the system
[assembly: RegisterFormValidationRule("ValueLiesBetweenValidationRule", typeof(ValueLiesBetween), "Closed interval validation", Description = "Checks whether the input lies in the specified closed interval.")]

namespace LearningKit.FormBuilder.CustomValidationRules
{
    [Serializable]
    public class ValueLiesBetween : ValidationRule<int>
    {
        // Defines a configuration interface for the rule
        // The EditingComponent attribute specifies which form component is used as an editing interface for the rule's properties
        [EditingComponent(IntInputComponent.IDENTIFIER, Label = "Minimum value", Order = 0)]
        public int MinimumValue { get; set; }

        [EditingComponent(IntInputComponent.IDENTIFIER, Label = "Maximum value", Order = 1)]
        public int MaximumValue { get; set; }

        // Gets the title of the validation rule as displayed in the list of applied validation rules
        public override string GetTitle()
        {
            return $"Value lies between [{MinimumValue};{MaximumValue}].";
        }

        // Returns true if the component's value lies between the specified boundaries
        protected override bool Validate(int value)
        {
            return (MinimumValue <= value) && (value <= MaximumValue);
        }
    }
}

```

After [registration](#registering-validation-rules), the validation rule is available on the validation tab of form fields based on form components with the _int_ type:

![Configuring the closed interval validation rule](https://docs.kentico.com/docsassets/13/defining-field-validation-rules/FormBuilderBasicValidationRule.png "Configuring the closed interval validation rule")

## Defining field comparison validation rules

Field comparison validation rules can compare submitted values from multiple fields against each other, which creates dependencies between fields in the form. For example, if field _X1_ contains value _Y_, and field _X2_  satisfies a given condition, the form can be submitted. All field comparison rules inherit from the **CompareToFieldValidationRule** base class that specifies the _type_ of form components for which they are applicable, and forces the implementation of methods required for the rule's functionality.

> **Info:** When validation rules of this type are added to a form field on the **Validation** tab, they automatically provide a Field drop-down selector that allows users to select a form field against which the submitted value is compared. The selector only offers form fields based on form components of the type corresponding to the type defined for the selected field comparison validation rule.

To define a field comparison validation rule:

1. Open your live site project in Visual Studio.
   - The validation rule base classes are available in the _Kentico.Forms.Web.Mvc_ namespace, which is provided by the _Kentico.Xperience.AspNetCore.WebApp_ or _Kentico.Xperience.AspNet.Mvc5_ NuGet package. For this reason, you need to define validation rules directly in your live site web application, or within a separate class library that has the appropriate NuGet packages installed.

2. Create a new class that inherits from **CompareToFieldValidationRule**.
   - Substitute the _TValu&#x65;_&#x67;eneric with the _type_ of form components to which the rule is applicable (e.g., basic data types such as _string_,_int_, _decimal)_. Validation rules do not support nullable types.

3. Annotate the class with the [**Serializable** attribute](https://docs.microsoft.com/en-us/dotnet/api/system.serializableattribute).

4. (Optional) Define custom properties and annotate them with the [EditingComponent](https://docs.kentico.com/13/developing-websites/form-builder-development/assigning-editing-components-to-properties.md) attribute to provide a configuration interface for users when adding validation rules on a form field's **Validation** tab.

   ```csharp

           // Defines a configuration interface for the rule
           // Uses the EditingComponent attribute to specify which form component is used to provide an editing interface for the property
           [EditingComponent(TextInputComponent.IDENTIFIER)]
           public string ConfigurableProperty { get; set; }


   ```

5. Override the following methods:

   - **GetTitle**– needs to return the title displayed when listing a field's applied validation rules, for example, '_The maximum length is 100 characters._'. The title can be localized by [using theResHelperclass](https://docs.kentico.com/13/multilingual-websites/setting-up-multilingual-websites/localizing-content.md).
   - **Validate**– contains the rule's validation logic. The method's **value** parameter contains the submitted value of the field. The value of the field selected for comparison is stored in the class's **DependeeFieldValue** property. The method needs to return either _true_, indicating the validation has succeeded, or _false_, indicating the validation has failed.

   ```csharp

           // Gets the title of the validation rule as displayed in the list of applied validation rules
           public override string GetTitle()
           {
               return "This title appears in the list of applied validation rules on the 'Validation' tab of individual form fields.";
           }

           // Contains custom validation logic
           // Invokes when validation occurs
           protected override bool Validate(string value)
           {
               return true;
           }


   ```

6. [Register the validation rule](#registering-validation-rules) in the system.

The validation rule is now registered in the system and ready to be applied to form components of the corresponding type [via the Form builder interface](https://docs.kentico.com/13/managing-website-content/forms/composing-forms.md).

### Example - Defining a field comparison validation rule

The following example demonstrates the implementation of a rule that validates whether the numeric value of a field lies within an interval defined by the value of another field and a specified boundary. The example implements the rule for form components of the _int_ type:

```csharp

using System;

using Kentico.Forms.Web.Mvc;

using LearningKit.FormBuilder.CustomValidationRules;

// Registers the validation rule in the system
[assembly: RegisterFormValidationRule("ValueOfDependeeLiesBetweenValidationRule", typeof(ValueOfDependeeLiesBetween), "Value of another field is between", Description = "Checks whether the value of the selected field lies on the specified interval given by the value of the selected field and the specified boundary.")]

namespace LearningKit.FormBuilder.CustomValidationRules
{
    [Serializable]
    public class ValueOfDependeeLiesBetween : CompareToFieldValidationRule<int>
    {
        // Defines a configuration interface for the rule
        // The 'EditingComponent' attribute specifies which form component is used as the property's value editor
        [EditingComponent(IntInputComponent.IDENTIFIER, Label = "Bound", Order = 0)]
        public int Bound { get; set; } = 0;

        // Gets the title of the validation rule as displayed in the list of applied validation rules
        public override string GetTitle()
        {
            return $"The submitted value must lie on the interval specified by the value of the selected field and {Bound}.";
        }

        // Validates the configured property values against the submitted value of the selected dependee field
        protected override bool Validate(int value)
        {
            if (Bound > DependeeFieldValue)
            {
                return (DependeeFieldValue <= value) && (value <= Bound);
            }
            else
            {
                return (Bound <= value) && (value <= DependeeFieldValue);
            }
        }
    }
}

```

After [registration](#registering-validation-rules), the validation rule is available on the validation tab of form fields based on form components with the _int_ type:

![Configuring the implemented field comparison validation rule](https://docs.kentico.com/docsassets/13/defining-field-validation-rules/FormBuilderDependingValidation.png "Configuring the implemented field comparison validation rule")

## Registering validation rules

To register a validation rule, annotate your validation rule _type_ with the **RegisterFormValidationRule** assembly attribute. This attribute ensures the validation rule is recognized by the system and available for [use in the form builder interface](https://docs.kentico.com/13/managing-website-content/forms/composing-forms.md). When registering the rule, specify the following parameters:

- **Identifier** – a unique _string_ identifier of the validation rule.
- **ValidationRuleType** – the _System.Type_ of the validation rule class.
- **Name** – used to set the name of the validation rule. Displayed when [adding validation rules](https://docs.kentico.com/13/managing-website-content/forms/composing-forms.md) on the _Form builder -> Validation_ tab in the administration interface.
- (Optional) **Description**– used to set the description of the validation rule. Displayed when adding validation rules on the _Form builder -> Validation_ tab in the administration interface.

> **Tip:** Both the **Name** and the **Description** parameters can be localized using resource string keys. See [Localizing builder components](https://docs.kentico.com/13/multilingual-websites/setting-up-a-multilingual-user-interface/localizing-builder-components.md).

The example below demonstrates the registration of a validation rule:

```csharp

// Registers the validation rule in the system
[assembly: RegisterFormValidationRule("CustomValidationRule", typeof(CustomValidationRule), "Custom validation rule", Description = "Contains custom validation logic.")]


```

The validation rule is now registered in the system. Users can include it when specifying field validation on the **Form builder** tab of the **Forms** application.
