Episerver Forms: Adding custom validators to existing elements

...

It's easy to extend Episerver forms with custom validation types. But it's a little bit harder to add the new validation types to the existing elements. In this blog post I'll add an ultra simple letter-only validation option to the existing TextboxElement.

I got this request from a customer yesterday, and I figured more could probably benefit from this approach.

Challenge: Add a number of custom form input validation options to existing form elements.

Now, Episerver Forms is very extendable. And it is quite easy to add your own validation - you simply have to create something that inherits ElementsValidatorBase or one of it's descendents. But in order to attach it to a form element type, the typical approach is to create a new element type.
There are numerous examples of this - and Episerver offers one as well: https://world.episerver.com/documentation/developer-guides/forms/creating-form-element-with-validator/.

However, what if you are perfectly happy with the built-in types, and simply want to extend it with another validation type - but you can't since it's already locked down by the [AvailableValidatorTypes] attribute (as most of the built-in are)?

Sure, you could inherit the class and make a minimalistic new type, but soon you'll get buried in a lot of elements - and getting the editors to pick the right one might not be easy. Of course there are hacks to hide the built-in elements (https://world.episerver.com/forum/developer-forum/episerver-forms/thread-container/2018/7/hiding-standard-formcontainerblock/) but I prefer this approach.

It's pretty straight forward. The IValidationService is in charge of getting the validators, and in the example below, I extend it with a dictionary of additional validators that'll get added after the regular logic.

The example validator I have added is a very simple LettersOnly validator for the textbox element - but it could have been any kind of validator.

The only code not included in the Gist here is the language text for UI display. 

 

Post Comments()

You might also like