ReactiveValidation icon indicating copy to clipboard operation
ReactiveValidation copied to clipboard

Add a new parameter to WithMessage

Open blahetal opened this issue 1 year ago • 2 comments

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

blahetal avatar Oct 31 '24 08:10 blahetal

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.

Karnah avatar Oct 31 '24 09:10 Karnah

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/....

blahetal avatar Oct 31 '24 09:10 blahetal

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.

Karnah avatar Nov 06 '24 18:11 Karnah

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?

blahetal avatar Nov 07 '24 09:11 blahetal

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.

Karnah avatar Nov 07 '24 09:11 Karnah

ok, thank you. this can wait

blahetal avatar Nov 07 '24 09:11 blahetal