Create and assign a custom field-type validator

Version: 9.0

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.

  1. In Visual Studio, create a project.

  2. In the Sitecore.Forms.Core.dll library, create a custom validation class, for example Custom.Form.Validators.DateInFutureValidator inherited from the Sitecore.Form.Core.Validators.FormCustomValidator.

  3. Create a validation method of the void type that receives the object and ServerValidateEventArgs parameter types.

    See a code sample:

    RequestResponse
    public 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;
        }
    }
    
  4. Compile your project to the /bin folder.

  5. In the content tree, navigate to the sitecore/System/Modules/Web Forms for Marketers/Settings/Validation folder and on the right pane, in the Folder tab, in the Options section, click on the BaseValidator button.

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

  7. In the Data section of the item, in the Assembly and Class fields, enter the appropriate values of the custom assembly.

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

    Note

    If you do not enter a message in the Text field, its value is copied from the Error Message field.

  9. 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 Picker folder.

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

Do you have some feedback for us?

If you have suggestions for improving this article,