开发者

Data validation in Silverlight 4 - Entity level validation vs ViewModel validation

开发者 https://www.devze.com 2023-02-13 17:02 出处:网络
I\'m working with Silverlight 4开发者_JS百科, MVVM, WCF RIA and Entity Framework. As I know, there are two ways to do data validation. First is entity level validation, second is write down validation

I'm working with Silverlight 4开发者_JS百科, MVVM, WCF RIA and Entity Framework. As I know, there are two ways to do data validation. First is entity level validation, second is write down validation logic in ViewModel.

Currently I create validation logic inside ViewModel, so I want to know pros and cons of each way.


DataAnnotation attributes can be applied to ViewModel too. But problems are the same:

  • Throwing of exceptions on validation errors - noise in the output window
  • Setting some default value to a property, it throws exceptions and set an invalid state
  • Impossible to validate a model completely and receive all its errors.
  • Impossible to add or clear errors in code.

The advantage is simplicity of data annotations in comparison with other ways.

On the other hand, the INotifyDataErrorInfo interface allows to perform validation asynchronously. As it was mentioned in other answer, if you want to check whether a username is already exist in the database, you can send a request to the service and add an error to the UI after receiveing an asyncronous callback.

I prefer to use INotifyDataErrorInfo and although it requires more code than data annotations, it can be reduced by creating a sort of generic validator class:

this.Validator = new ModelValidator<ProfileViewModel>(this);
this.Validator.AddValidationFor(() => this.SelectedCountry).NotNull().Show("Select country");
this.PropertyChanged += new PropertyChangedEventHandler(this.ValidateChangedProperty);


It's a bit of a cop out but you'll probably end up needing to do both types of validation.

Entity level validation is useful as you only have to define it in one place and you get UI validation messages and entity validation before it gets saved to the database (assuming that data is being saved to a db).

The trouble is that entity level validation is fairly basic and you'll probably need to make some service calls to do custom validation (for example, we validate that a user exists on our network for a provided username in our create user form). This is where you need to do validation in your VM.

0

精彩评论

暂无评论...
验证码 换一张
取 消