Reputation: 9648
I'm working with Silverlight 4, 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.
Upvotes: 2
Views: 2752
Reputation: 14037
DataAnnotation
attributes can be applied to ViewModel
too. But problems are the same:
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);
Upvotes: 2
Reputation: 6052
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.
Upvotes: 2