I have problem with Fluent Validation.
I want to check the validation so the property must be filled greater than another property.
here is the code :
public decimal? MonthlySalesNet { get; set; }
public decimal? MonthlySalesGross { get; set; }
and here is the validation :
RuleFor(x => x.MonthlySalesGross.Value).GreaterThan(x => x.MonthlySalesNet.Value)
.When(x => x.MonthlySalesGross != null && x.MonthlySalesNet != null)
.WithMessage("blahblah");
the validation was working but the message was not shown. am I missing something?
when I was changed decimal to not nullable type and reconfigure the validation, the error message validation was shown. it`s weird for me,,Thanks
(I posted the same answer over on the FV forum)
The message doesn’t display because it thinks it’s associated with the wrong property. When you use RuleFor(x => x.MonthlySalesGross.Value), it associates the rule with a property called “Value” rather than with the MonthlySalesGross property.
FluentValidation v3 adds better support for nullables (I blogged about this here), but at present this only works with constant values, not expressions that reference other properties. I’m planning to expand the nullable support to work with cross-property validators with v3.1, but for now you can work around this by manually overriding the property name. This will re-associate the error with the correct property:
(note that you also have to include a null check with a When clause).