2

I have started using the MVVM pattern.

Everything is fine if I want to display data, I can just find the item source to a object and everything displays as it should.

My question is how do I validate input data? E.g. I have 2 input fields and I need to ensure the fields are populated and ensure the item does not already exist.

Can I just forward the content of the fields to my view model or is there a different/better way?

gurehbgui
  • 14,236
  • 32
  • 106
  • 178
  • If I understand your intent correctly this is a duplicate. http://stackoverflow.com/questions/4152346/mvvm-validation – Eric LaForce Nov 08 '11 at 02:23

1 Answers1

3

Your ViewModel should implement IDataErrorInfo to do validation.

Example code in C#:

public class EmployeeViewModel : IDataErrorInfo, INotifyPropertyChanged
{
    public string FirstName { /* get set and NotifyChanged here...*/ }

    public string LastName { /* get set and NotifyChanged here...*/ }

    public string Error
    {
        get { return error; }
    }

    public string this[string columnName]
    {
        get 
        {
            string error = string.Empty;
            switch (columnName)
            {
                case "FirstName":
                    if(string.IsNullOrEmpty(this.FirstName))
                        error = "FirstName can not be blank";
                    else if (this.FirstName == "Ekk")
                        error = "Ekk is my name, you should change!";
                    break;
                case "LastName":
                    if(string.IsNullOrEmpty(this.LastName))
                        error = "LastName can not be blank";
                    break;
            }
            return error;
        }
    }
}
Ekk
  • 5,627
  • 19
  • 27