Walkthrough: Creating a custom validator based on the existing regular expression validation
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.
Create a validation item
To create a validation item:
-
In the Content Editor, go to
/sitecore/System/Settings/Forms/Validations
. -
Right-click Validations, click Insert, Insert From Template.
-
In the Insert from Template dialog box, go to
/System/Forms
and click the Validation template. -
In the Item Name field, enter Name Validation and click Insert.
-
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
). -
In the Message field, enter an error message, for example, Contains an invalid name.
-
In the Parameters field, set the regular expression pattern to validate names:
RequestResponseshell{"regularExpression":"^[a-zA-Z]*$"}
-
Save your changes.
Modify the field type
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:
-
Go to
/sitecore/System/Settings/Forms/Field Types/Basic/Single-line text
. -
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.
-
Save your changes.
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.