Defining field validation rules

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 Kentico, 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 decimalvalue 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:

MVC Areas

Field validation rules are designed to be used in the global scope and therefore must be registered in the application root of your MVC project (not in an MVC Area). Registering field validation rules in MVC Areas may lead to unexpected behavior.

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<TType> 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 MVC project in Visual Studio.

  2. Create a new class that inherits from ValidationRule<TValue>. Substitute the TValuegeneric with the type of form components for which the rule is applicable (e.g., basic data types such as string,intdecimal).

  3. Annotate the class with the Serializable attribute.

  4. (Optional) Define custom properties and annotate them with the EditingComponent attribute to provide a configuration interface for users when adding validation rules on a form field’s Validation tab.

    
    
    
             // 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.
    • 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.



        // 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;
        }



  1. Register the validation rule 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.

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:




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, 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

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<TValue> 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.

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 MVC project in Visual Studio.

  2. Create a new class that inherits from CompareToFieldValidationRule<TValue>. Substitute the TValuegeneric with the type of form components to which the rule is applicable (e.g., basic data types such as string,intdecimal).

  3. Annotate the class with the Serializable attribute.

  4. (Optional) Define custom properties and annotate them with the EditingComponent attribute to provide a configuration interface for users when adding validation rules on a form field’s Validation tab.

    
    
    
             // 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.
    • 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.



        // 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;
        }



  1. Register the validation rule 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.

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:




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, 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

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. 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 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.

Both the Name and the Description parameters can be localized using resource string keys. See Localizing MVC builder components.

The example below demonstrates the registration of a validation rule:




// 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.