Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing IDataErrorInfo in a view model

I have a ViewModel class with a Phone object as one of its properties , my main window data context is set to the ViewModel, do I need to implement IDataErrorInfo on the underlying Phone model class or the ViewModel class that contains the Phone property?

Also what would be the correct way to bind the textbox I'm trying to validate to my ViewModel.NewPhone.StringProperty?

Many thanks

like image 977
Michael Harper Avatar asked Oct 28 '12 22:10

Michael Harper


1 Answers

The decision of where to implement IDataErrorInfo really depends on your application's logic. For example, you could have your Phone class implement it in a way that doesn't allow any invalid phone numbers, but in your viewmodel you'd like to only allow numbers from the US.

Usually a good practice is to implement IDataErrorInfo in both your model and viewmodel, and in case no error was found by the viewmodel, forward the request to the model. Then you'll bind to the viewmodel as usual.

public string this[string propertyName]
{
    get
    {
        if (propertyName == "PhoneNumber")
        {
            if (!IsUSNumber(PhoneNumber))
            {
                return "Non-US number.";
            }
        }

        // No validation errors found by the viewmodel
        // Forward to model's IDataErrorInfo implementation
        return Model[propertyName];
    }
}

I recommend having the model implement the basic validations which are relevant for every phone, like phone number format, and have the viewmodel implement the view-specific validations that may vary from view to view, such as only allowing US phone numbers or numbers that belong to a certain provider.

like image 160
Adi Lester Avatar answered Sep 21 '22 11:09

Adi Lester