Create and assign a custom field-type validator
The Web Forms for Marketers module contains a number of field-type validations by default. When you assign validations to a field, the changes you have made to the field affect all the forms on your website that use it. In addition to the default validations, you can also create your own custom field-type validations.
You may want to create a custom field-type validator in case that default validators do not suit your needs. For example, you might want to ensure that all DatePicker fields on your website validate that the chosen date is in the future.
-
In Visual Studio, create a project.
-
In the
Sitecore.Forms.Core.dlllibrary, create a custom validation class, for exampleCustom.Form.Validators.DateInFutureValidatorinherited from theSitecore.Form.Core.Validators.FormCustomValidator. -
Create a validation method of the void type that receives the object and
ServerValidateEventArgsparameter types.See a code sample:
RequestResponsepublic class DateInFutureValidator : FormCustomValidator { public DateInFutureValidator() { this.ServerValidate += this.OnDateValidate; } private void OnDateValidate(object source, ServerValidateEventArgs args) { DateTime time = Sitecore.DateUtil.IsoDateToDateTime(args.Value).Date; if (time >= DateTime.UtcNow) { args.IsValid = true; return; } args.IsValid = false; } } -
Compile your project to the /bin folder.
-
In the content tree, navigate to the
sitecore/System/Modules/Web Forms for Marketers/Settings/Validationfolder and on the right pane, in the Folder tab, in the Options section, click on the BaseValidator button. -
In the Message dialog box, enter a name for the new item, for example Date In Future and click OK. This creates a new item based on the BaseValidator template.
-
In the Data section of the item, in the Assembly and Class fields, enter the appropriate values of the custom assembly.
-
In the Error Message and Text fields, enter a relevant message for the visitor, for example, The date is in the past, please select one in the future.
NoteIf you do not enter a message in the Text field, its value is copied from the Error Message field.
-
On the left pane, navigate to the relevant field type, for example Date Picker, located in the
/sitecore/system/Modules/Web Forms for Marketers/Settings/Field Types/Simple Types/Date Pickerfolder. -
On the right pane, in the Behavior section, in the Validation field, select the validator that you have created, for example, Date In Future and add it
to the Selected field.Now that you have created the validator, you can assign it to a particular field type on your forms.


