Karnah / ReactiveValidation

A small validation library for WPF and Avalonia which uses a fluent interface and allows display messages near controls in GUI with MVVM
MIT License
73 stars 11 forks source link

Add a new parameter to WithMessage #35

Open blahetal opened 1 week ago

blahetal commented 1 week ago

Hello, would you consider tweaking the function WithMessage a bit. I would like to provide a custom error message with a computed value derived from the object (view mode) being validated. Current version allows to provide a static text

RuleFor(vm => ...).LessThan(vm =>...).WithMessage("Error");

I would like to do something like this

RuleFor(vm => ...).LessThan(vm =>...).WithMessage(vm =>$"Error{vm....}");

Thanks, Libor

Karnah commented 1 week ago

Hello, @blahetal.

.WithMessage(vm =>$"Error{vm.SomeProperty}")

As I understand, SomeProperty is also INotifyPropertyChanged property, so each time it's changed, the error message should also change? Hmm, I'll try to find a better way to implement this.

blahetal commented 1 week ago

Hello, @blahetal.

.WithMessage(vm =>$"Error{vm.SomeProperty}")

As I understand, SomeProperty is also INotifyPropertyChanged property, so each time it's changed, the error message should also change? Hmm, I'll try to find a better way to implement this.

What I am trying to do is that in the error message I would like to display a value that is computed from other values present in the view model that is being passed to the RuleFor. Eg.

ViewModel - has three doubles A, B, C - they implement INotifyPropertyChanged and user can change all of them in a view/form

RuleFor(vm => vm.A).LessThan(vm => ComputeSmth(vm.B, vm.C)).WithMessage(vm =>$"The value A does not match the computed result when B = {vm.B} and C = {vm.C}");

double ComputeSmth(double value1, double value2) => ....return smth based on the values of value1 and value2...;

I think passing the VM to WithMessage would be enough, no? Like you are doing it in other methods LessThan/Between/....

Karnah commented 1 week ago

I think passing the VM to WithMessage would be enough, no? Like you are doing it in other methods LessThan/Between/....

I've thought about cases like that: RuleFor(vm => vm.A).LessThan(vm => vm.B).WithMessage(vm =>$"{vm.C}");, Here property C is not part of validation process, and if default mechnism will be used than property A still will be revalidated. It's better rebuild only message.

blahetal commented 6 days ago

Hi, not sure what you mean. Maybe a point you made in one of your previous messages when C changes, it would trigger validation of A again?

Karnah commented 6 days ago

Hi! Yes, you understood me correctly. There's no need to revalidate A when C changed, so it's better to only change message. Unfortunately, I don't have much time now, so I can research this problem a bit later.

blahetal commented 6 days ago

ok, thank you. this can wait