Validate using attributes in MVVM

Introduction

The goal here is to create an easy way to add validation to properties when working with xaml and MVVM.

I have chosen this approach:


[ValidateMethod("ValidateFirstName")]
public string FirstName
{
    get { return firstName; }
    set { SetProperty(ref firstName, value); }
}

public string ValidateFirstName()
{
    if (string.IsNullOrEmpty(FirstName))
    {
        return "First name is mandatory";
    }

    return string.Empty;
}

Simple attribute referring to a method by string. The method then handles the validation.
The reason for choosing attributes is to make validation on properties easy to spot for all developers reading the code.
Continue reading “Validate using attributes in MVVM”

P.S Make sure you follow me on twitter @danielvistisen for updates on new posts.

Validate using attributes in MVVM