Can anyone tell me which is a better approach for Validation in WPF.
- Implementing IDataErrorInfo
- Creating ValidationRule
- Throwing Exceptions
in terms of performance, memory leaks, code maintainability and re-use.
Can anyone tell me which is a better approach for Validation in WPF.
in terms of performance, memory leaks, code maintainability and re-use.
This is kind of a complex request, and honestly it'll probably vary based on preference more than anything else. But, here's my understanding:
ValidationRules are older than IDataErrorInfo (I believe the latter was introduced in .Net 3.5). Based on this alone, it would seem that the WPF team prefers IDataErrorInfo. But the truth is they're built for different things. If you have MVVM or an equivalent pattern, IDataErrorInfo is superior for errors in the model (like, say, a negative age) whereas ValidationRules are superior for errors in the view (say, an age of ☃). It's of course possible to have the ValidationRules perform "business logic" checks, or to have the IDataErrorInfo tell you "a unicode snowman is not a valid age", but you'll (probably) get the best maintainability by keeping to this pattern.
But don't use exceptions for validation beyond the initial testing to see what exact conditions you should be testing for.
It is not good idea to use exception for error handling. Using exception will reduce performance. It is a matter of selecting and Implementing IDataErrorInfo or Creating ValidationRule.
IDataErrorInfo
Validation Rule
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.