dotnet
dotnet copied to clipboard
Support for FluentValidation in ObservableValidator
Overview
ObservableValidator uses System.ComponentModel.DataAnnotations.Validator, and is tough to replace - a call to (static) Validator.Validate is not substitutable. For straightforward implementation of validation, this is VERY useful - because annotations can be used in the viewmodel itself to build complex validation rules very quickly.
However, my organization uses FluentValidation very widely to validate model classes across many contexts. One such context that would be very nice to re-use is the MVVM UI itself - rather than needing to duplicate the logic using DataAnnotations in each VM.
The solution I have in mind now is to wrap the ObservableValidator class, but even then the Validate methods do not seem to lend themselves to this easily.
API breakdown
public class ObservableValidator : ObservableObject, INotifyDataErrorInfo
{
private IValidator _validator;
public ObservableValidator2(IValidator validator)
{
_validator = validator;
}
}
Usage example
public class BarViewModel : ObservableValidator
{
public BarViewModel(AbstractValidator<Bar> validator) : base(validator)
{
}
}
Breaking change?
I'm not sure
Alternatives
Wrap ObservableValidator and override methods as required to integrate FluentValidation's AbstractValidator<T> or IValidator<T> functions.
Additional context
Unfortunately the static Validator does not implement an interface. Perhaps the Validator would need to be wrapped to implement a common interface with AbstractValidator<T> or IValidator<T> (from FluentValidation).
In order to prevent a dependency to FluentValidation, perhaps a custom IValidator interface could be specified for this library, and it would be the responsibility of the creator of the FluentValidation AbstractValidator<T> class to implement this interface (it would be nice if it mostly matched, already, of course!)
Help us help you
Yes, I'd like to be assigned to work on this item
After some testing, this may be complicated by the fact that my ViewModels are generally wrappers for their models - so in that case how could I flexibly define how to validate against the model's validator - especially when the model itself does NOT have the new value of the property being validated - still thinking on it.
Any thoughts would be appreciated! Maybe I'm missing something very straightforward, here.