Walkthrough: Creating a custom validator based on the existing regular expression validation

Abstract

Add field validation using an existing validator.

Web form validation ensures a website visitor enters the correct value in a field on a web form. This walkthrough describes how to add a name validator based on the existing regular expression validation. This validator validates the input string of single-line text fields for valid names.

Follow these steps to create any validator based on regular expression validation. You only need to set the regular expression pattern to validate the input based on your requirements.

To create a validation item:

  1. In the Content Editor, go to /sitecore/System/Settings/Forms/Validations.

  2. Right-click Validations, click Insert, Insert From Template.

  3. In the Insert from Template dialog box, go to /System/Forms and click the Validation template.

    Insert from Template dialog box with Validation template selected
  4. In the Item Name field, enter Name Validation and click Insert.

  5. With the item you just created selected in the content tree, click the Content tab and, in the Settings section, in the Type field, set the value to the existing regular expression validation class type name (for example, Sitecore.ExperienceForms.Mvc.Models.Validation.RegularExpressionValidation,Sitecore.ExperienceForms.Mvc).

  6. In the Message field, enter an error message, for example, Contains an invalid name.

  7. In the Parameters field, set the regular expression pattern to validate names:

    {"regularExpression":"^[a-zA-Z]*$"}
    Name Validation item settings
  8. Save your changes.

You must modify the field type to use the new validation. The single-line field type is used in this procedure as an example.

To modify the field type:

  1. Go to /sitecore/System/Settings/Forms/Field Types/Basic/Single-line text.

  2. On the Content tab, in the Settings section, in the Allowed Validations field, double-click the new validation item you just created (that is, Name Validation) to move it to the Selected list.

  3. Save your changes.

Note

Validators that are based on the same validation type must not be enabled together on a field by the Form designer. For example, Email validator and Phone number validator are both based on regular expression validation and must not be enabled at the same time on a specific field. To prevent enabling same type validation on the field by the Form designer, we recommend that you do not add validators of the same type to the allowed validations list.