Walkthrough: Creating a custom validation

Last updated Friday, October 27, 2017 in Sitecore Experience Platform for Developer
Keywords: Configuration, Forms

A web form validation can help a website visitor enter a correct value in a field on a web form. This walkthrough describes how to implement a custom validation that validates names. It validates the input string of the Single-line text field for valid names.

This walkthrough describes how to:

Create the validation class

When you create a custom validation, you must create a class that inherits from the ValidationElement<string>.

To create the validation class:

  1. Create the NameValidation class and inherit from ValidationElement<string>.
  2. Reference the Sitecore.ExperienceForms.Mvc package and System.ComponentModel.DataAnnotation assembly.
  3. Implement the Validate method for server validation.
  4. Implement the ClientValidationRules property for client validation.
  5. Override the Initialize method to initialize properties from the validated model (for example, the title of the field).
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Text.RegularExpressions;
    using System.Web.Mvc;
    using Sitecore.ExperienceForms.Mvc.Models.Fields;
    using Sitecore.ExperienceForms.Mvc.Models.Validation;
    namespace Sitecore.ExperienceForms.Samples.Validation
    {
        public class NameValidation : ValidationElement<string>
        {
            private const string NamePattern = "^[a-zA-Z ]*$";
            public NameValidation(ValidationDataModel validationItem) : base(validationItem)
            {
            }
            public override IEnumerable<ModelClientValidationRule> ClientValidationRules
            {
                get
                {
                    var clientValidationRule = new ModelClientValidationRule
                    {
                        ErrorMessage = FormatMessage(Title),
                        ValidationType = "regex"
                    };
                    clientValidationRule.ValidationParameters.Add("pattern", NamePattern);
                    yield return clientValidationRule;
                }
            }
            public string Title { get; set; }
            public override ValidationResult Validate(object value)
            {
                if (value == null)
                {
                    return ValidationResult.Success;
                }
                var regex = new Regex(NamePattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
                var stringValue = (string)value;
                if (string.IsNullOrEmpty(stringValue) || regex.IsMatch(stringValue))
                {
                    return ValidationResult.Success;
                }
                return new ValidationResult(FormatMessage(Title));
            }
            public override void Initialize(object validationModel)
            {
                base.Initialize(validationModel);
                var obj = validationModel as StringInputViewModel;
                if (obj != null)
                {
                    Title = obj.Title;
                }
            }
        }
    }

Create the validation item

To create the validation item:

  1. Navigate to /sitecore/system/Settings/Forms/Validations.
  2. Right-click Validations, click Insert, and click Insert from Template.
  3. Select the /System/Forms/Meta Data/Validation template.
  4. In the Item Name field, enter Name Validation and click Insert.

    Picture 1

  5. Navigate to the item you just created and in the Settings section, in the Type field, set the value to the class type name.
  6. In the Message field, enter an error message, for example, contains an invalid name.

    Picture 2

Modify the field type

Now you must modify the field type for which you want to use the new validation. In this example, we only want to use the new validation for the single-line field type.

To modify the field type:

  1. Navigate to /sitecore/system/Settings/Forms/Field Types/Basic/Single-line text.
  2. In the Settings section, in the Allowed Validations field, select the new validation item, for example, Name validation.

    Picture 3

Add the validation to the field editor

Most elements have the FieldValidation control added to the field editor. If the validation is not shown by default, you can add the validation to the field editor:

Note

For the example in this walkthrough, you must have the Sitecore Rocks Visual Studio plug-in.

  1. Switch to the Core database and in the Content Editor, navigate to /sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Settings and click the element to which you want to add the validation.
  2. In the ControlDefinitions field, add the FieldValidation control definition. You can find the control definition at: /sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Common/Validation/FieldValidation

    Picture 4

Now you can use name validation on your forms to validate the input string of the Single-line text field.

Send feedback about the documentation to docsite@sitecore.net.