Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement data validation in model of MVVM?

I have an MVVM application which requires data validation. I would like to keep the validation in the model, so the model can be easily reused with other view models without having to duplicate the validation code. Most examples of data validation with WPF either have the validation done in the view model in a MVVM setup, or data validation done in the model when the model is directly bound to the view and a view model is not used.

I would like to have the data validation in my model, have the view model expose my model to the view, and have the view still be able to receive validation feedback from the model. I am planning on either using IDataErrorInfo or Data Annotations for my validation. I have found some examples of this being done, but neither approach seems ideal.

It is accomplished here with Data Annotations, though it took a moderate amount of custom code.

I like this approach with IDataErrorInfo better as it does not involve custom code, however I don't know if I am comfortable with the approach taken, where the entire model is exposed as a single property to the view, versus exposing just the required individual properties.

Is there a better or more recommended way to accomplish this?


1 Answers

The data annotations method you've linked is somewhat redundant as the framework already has the concept of bindable validation rules (see Taking data binding, validation and MVVM to the next level). The only time the data annotations approach will be useful is when validating in a spot that is completely divorced from the UI.

Aside from those two options, using IDataErrorInfo is your only other choice. Note that you are not "exposing the entire model to the view as a single property", rather you are using an interface to expose your custom entity to the binding framework - there's a big difference. If you choose this method then make sure you use resource strings to hold your error messages rather than using hard coded text. The IDataErrorInfo approach is useful if you have different people working on the view and viewmodel - the person doing the view doesn't need to know anything about the specific validations of the viewmodel.

like image 184
slugster Avatar answered Oct 22 '25 01:10

slugster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!