EPiServer Forms: Adding custom client side validation to form field (Luhn algorithm)

When you’re developing custom EPiServer Forms field blocks you sometimes need to add your own custom validation as well. In this article you’ll see an example of how to add client side validation for the Luhn algorithm in a custom textfield block.

Adding custom client side validation to EPiServer Forms field blocks

Adding client side validation to your custom fields is not that difficult. All you’ll have to do is create a custom JavaScript file in your solution with code like below. The first part of the script only verifies that EPiServer’s scripts were loaded correctly, giving your a useful error message if they weren’t. You’ll have to move all the way down to line 34 for things to get interesting (past the Luhn algorithm which was just added for completion).

Add your own custom validators as in the bottom of the script above, and then extend EPiServer Form’s existing validator array with them. It is important that you use the fully qualified name for your custom validators (that’s the namespace plus the class name of the validator class in your solution). EPiServer will then automatically map your field’s validator to whatever function you decide to add here. The parameters fieldName and fieldValue are rather self explanatory. The validatorMetaData contains useful things like your validation message as shown above.

Making EPiServer aware of your client side JavaScript validation

To make EPiServer actually run your custom client side validation, you’ll need to register it as an external view mode resource. This may be done by adding a service configuration like below.