Fixing .NET validation using vue.js

Recently, we’ve created the website for Nederlandse Loterij. This website contains static pages and multiple forms for account management as well as some more dynamic features. We decided to use vue.js as a client-side framework.

Why vue.js?

Currently at Q42 we mainly use vue.js and React as JavaScript frameworks, and considering this website would be actively maintained for the following years by ever-changing teams we needed a no-nonsense framework to help keep the codebase maintainable. We knew that for this customer we wanted to use the fancy new .NET Core server framework running on the Azure cloud and that we wanted to use as much as the native .NET features as possible. Among these features were the Razor template engine and the .NET model validation attributes for validation. After a quick evaluation we found vue.js to be the best tool for the job, since it’s easy to learn and supports server-rendered HTML quite well.

Using the Razor template engine with vue.js required a few workflow adjustments. The usage of client-side templates would be reduced to a minimum, instead we made extensive use of the inline-template feature of vue.js to make sure components were correctly bound to the JavaScript logic.

Solving the validation problem

And here we encountered a problem: validation. The .NET Core framework includes a powerful set of validation features. The major advantage of using these .NET validation attributes is that validation rules are only present in the .NET Model of the form, but are validated on both the server and the client.

Example of .NET validation attributes in C#

Microsoft has a guide on how to setup client-side validation using jQuery, jQuery validate and jQuery validate unobtrusive libraries. We were not very fond of including a second JavaScript framework into our website, since it introduces a lot of additional kilobytes to transfer and can introduce issues when accessing fields from our vue.js logic. For this reason, we’ve created a new library called “vue-dotnet-validator”, which is a very small vue.js library that supports validation attributes that is rendered using the Razor template engine.

Vue-dotnet-validator

The vue-dotnet-validator library supports quite some of the native .NET validation attributes and has been written to be easily extendible with custom validators so it can be used in any Razor rendered form.

During the project we’ve created multiple forms using the vue-dotnet-validator, with multiple custom validators, and overall we’re really happy with the result. It helped us create forms without the hassle of implementing duplicate validation rules on both the client and server or having to deal with multiple JavaScript frameworks.

Including vue-dotnet-validator in your client-side JavaScript
Example of the additional HTML to make vue-dotnet-validator work

For more info about including the vue-dotnet-validator in your own project, see the github page.