Validation in WPF - Custom validation rule or IDataErrorInfo
Asked Answered
M

3

9

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.

Maintain answered 5/12, 2010 at 13:15 Comment(0)
T
21

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.

Thalassography answered 5/12, 2010 at 23:50 Comment(3)
One potential benefit from using ValidationRule is that you can check value correctness BEFORE ViewModel is changed to improper value.Profusion
I think ValidationRules are only appropriate if you're not using MVVM. If you use a ValidationRule to prevent data entered in the view from getting into the view model, the view model is no longer modeling the view. It's hard enough to understand all this stuff without making it more opaque.Thalassography
but ValidationRule seems the only way to customize error messagesLlamas
E
1

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.

Exergue answered 30/9, 2013 at 3:45 Comment(0)
H
-1

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

Hydracid answered 5/12, 2010 at 13:22 Comment(1)
I am not sure I completely understood your answer: I can implement IDataErrorInfo, or inherit from ValidationRule and override 'Validate' method... I am not using them both at the same time. Am I wrong?Maintain

© 2022 - 2024 — McMap. All rights reserved.