Custom validators with Episerver Forms

A few weeks ago Episerver Forms was released. We have seen several blogs about creating custom forms types like a Color Picker or a Constrained Textbox.
But what about creating your own validators?

To create you own validator simply inherit from ElementValidatorBase.
You can also use RegularExpressionValidatorBase, which itself inherits from ElementValidatorBase, if you want to use a regular expression for validation.

In this example I will validate a Dutch postal code.

We override the model to set our regular expression.
The GetRegularExpressionValidationModel takes two argument. One regex string for DotNet (dotnetPattern) and one regex string for JavaScript (jsPattern).

Add the following lines to you language file. Use the full namespace of your validator.

After compiling, the new validator is immediately available in the UI.

However it will only give us server side validation, so we need to register our validator for client side validation.

When you look at the EpiserverForms.js file you will see that all the client side validators are added to the Validator list.
So we have to add our validator too. This can be done with a fews line of JavaScript

Again, be sure to use the full namespace of your validator.

Now that we have the JavaScript in place we have to make sure it it loaded when forms are used. This can be done by implementing IViewModeExternalResources

That’s it! We now have both server and client side validation!

  • K Khan

    Cool.

  • very nice! 🙂
    think i’ll need to dig deeper to see how you can avoid language Xml file – and instead provide validation error message via some strongly-typed localized resources 😉