I’m working on a project using WPF and MVVM with Entity Framework 4.3, and I would like to know how can I perform business logic validation implementing the IDataErrorInfo interface.
All of my models (POCO classes) are implementing it in order to perform raw validations, like maxlength, non-negative numbers, and so on…
But what about bussiness logic validation, such as to prevent duplicate records?
Imagine I have a textbox for a material “reference”, which must be unique, defined liked this:
<TextBox Text="{Binding Material.Reference, ValidatesOnDataErrors=True, NotifyOnValidationError=true,
UpdateSourceTrigger=PropertyChanged}">
The model will successfully validate the reference’s length, but if there’s already a material in my viewmodel’s materials observablecollection, how should I notify the user of this fact from my ViewModel, yet taking advantage of the IDataErrorInfo messages?
I’ve done this in the past by exposing a validation delegate from my models that my ViewModels can hook into for additional business logic validation
The end result ends up looking like this:
Most of my models inherit from a generic base class, which includes this validation delegate. Here’s the relevant code from that base class, taken from my blog article on Validating Business Rules in MVVM
This allows me to keep the basic data validation in my Models, and my ViewModels can attach any customized business logic validation they want to the Model as well.