Introducing MVVM Validation Helpers

In this post I would like to introduce MVVM Validation Helpers - a lightweight library that helps reduce boilerplate when implementing validation in your XAML (WPF/Silverligh/UWP/Xamarin) MVVM applications.

In MVVM you would typically implement the INotifyDataErrorInfo interface in your view models. Among other validation techniques, this option provides the greatest degree of flexibility and the most suitable for MVVM.

However, this interface is very minimalistic and low-level. It is not very convenient to implement and work with. So, in order to make it easier I have created a small library that allows you to implement various validation scenarios more easily and with less boilerplate.

With this library you can:

  • Define all your validation rules conveniently in one place. Such rules can target the entire object (view model), specific property, several dependent properties or any other target;
  • Validate a specific target or the entire object and get the validation result back without worrying what rules need to be checked, in what order, etc.;
  • Get the current validation state (valid or errors if not valid) at any time for a specific target or the entire object without performing the validation (for example in a CanExecute method of a an ICommand);
  • Subscribe to an event that indicates that validation result has changed. It might be useful, for example, when you want to display a "live" validation summary.

With this library you have total control over when to perform the validation. For example, in some cases you want to do it in the property setter, in others only when the user clicks the Save button.

It also supports asynchronous validation rules for the cases when you need to perform a server call to validate the target.

The examples of how to use the library can be found on GitHub. Also you can download the source code of the library that contains a fully working example of a simple registration form with validation that demonstrates how to use the library.

The library is also available as a NuGet package at https://nuget.org/packages/MvvmValidation.

Pavlo Glazkov

Pavlo Glazkov

Programmer. Full stack, with a focus on UI. JavaScript/TypeScript, Angular, Node.js, .NET

Read More