Implementing IDataErrorInfo in a view model
Asked Answered
M

1

6

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

Merengue answered 28/10, 2012 at 22:44 Comment(0)
C
10

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.

Corinacorine answered 29/10, 2012 at 7:59 Comment(3)
Nice explanation, especially the use of an easy-to-understand and concrete usage example. Thanks.Duumvirate
I've been looking for an example that showed how to do validation on view as well as the viewmodel. Thank youJemina
@Adi Lester I do not understand your example. You are showing a getter; but how can a getter do the validation instead of the setter? I'd understand your example if it were a getter, but can a getter return a (string) value?Figured

© 2022 - 2024 — McMap. All rights reserved.