Question

As a new WPF programer I cant find the difference between two different way to validate user input:

What are the pros and cons of writing custom validation rule against implementing IDataErrorInfo, and vice versa? WhenShould I prefer one over the other?

Update:

Though I got my answer already, I found related article that may help others.

Was it helpful?

Solution

Basically, if you implement IDataErrorInfo, validation is implemented in the bound object, whereas if you implement validation rules, validation is implemented in objects attached to the binding.

Personally, if you're using MVVM, I think you'd have to be crazy to ever use anything except IDataErrorInfo. You want validation to live in the view model. If it's in your view model, it's centralized and it's testable. If it's in your view, then your validation logic can be wrong, or missing, and the only way to find it is by manually testing your view. That's a huge potential source of avoidable bugs.

There are places where it makes sense to use validation rules - if, for instance, you're building a UI around dumb objects (an XmlDataSource, for example). But for most production applications, I wouldn't go near it.

OTHER TIPS

IDataErrorInfo

  • Validation logic keep in view model and easy to implement and maintain
  • Full control over all fields in the viewmodel

Validation Rule

  • Maintains the validation rule in separate class
  • Increase re-usability. For example you can implement required field validations class reuse it throughout the application.

My opinion is, for common validation like required field validations, email address validattions you can use validation rule. If you need to do custom validations like range validations , or whatever custom validation use IDataerrorinfo.

You implement IDataErrorInfo to be able to use databinding with eas. You still build your custom validation rules.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top