Custom WFFM Field Validation in Sitecore 8.1 MVC Solutions

I recently needed to create a custom email validation method in one of my sites to prevent users from submitting email addresses with blacklisted domains. When I tried to accomplish this, I found it difficult to find thorough documentation on what I needed to do. The Sitecore WFFM Field Type items have a section for Validation, and there is a folder of Validation items where custom items can be created, so this seemed like the obvious path forward. However, creating a BaseValidator item under /sitecore/system/Modules/Web Forms for Marketers/Settings/Validation/ and selecting it in the Validation field on my Field Type item did not work; I created a custom validation class in my code (public class EmailValidation : FormCustomValidator) and set my BaseValidator item to use it, but the code was not getting hit when I submitted my form.

validator

Some digging found this blog post, which was hard to find at first since the title didn’t explicitly reveal it related to the issue at hand, but ended up providing the solution.

In Sitecore 8.1, the MVC implementation of WFFM does not use the validation item structure /sitecore/system/Modules/Web Forms for Marketers/Settings/Validation for field validation. Instead, it uses Attributes on the Field Type class to do server side validation. This looks like:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public sealed class CustomValidationAttribute : DynamicValidationBase {

protected override ValidationResult ValidateFieldValue(IViewModel model, object value, ValidationContext validationContext) {

if (value == null || [error condition]){

return new ValidationResult(“error message”);

}
return ValidationResult.Success;

}

}

Then on the custom Field Type class, you just add a tag for the attribute, which maps to the Attribute item you’ve created:

public class EmailBlacklist : Sitecore.Forms.Mvc.ViewModels.Fields.EmailField {

[CustomValidation]
public override string Value { get; set; }

}

The field item in Sitecore:

field item

And that’s it! When I submit my form, it hits the Attribute code, and the error message string passed into the ValidationResult displays under the field if there is an error, which allows you to return different conditional error messages.

Author: ericastockwellalpert

.NET Developer and Sitecore MVP 2019-2020

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s