Skip to content

validating property updates

vijay@envivo edited this page May 21, 2026 · 8 revisions

Validating property updates

A quick option is to add validation code to property setters. If the validation fails, the UI will present a message immediately:

public string FirstName
{
    get => _FirstName;
    set
    {
        if (string.IsNullOrEmpty(value))
        {
            var message = "This value must be provided";
            throw new ArgumentNullException(nameof(FirstName), message);
        }
        _FirstName = value;
    }
}

Using Specifications for rules

To have your model truly reflect the domain, consider extracting the logic into a Specification class. See the Specifications section for more information.

The following example shows how an object uses a Specification for validation. The Specification is passed using property injection (you can also use constructor injection if you wish):

using System;

public class NameInfo
{
    private string _FirstName;
    private string _LastName;

    ...

    /// <summary>
    /// Used to check that names are valid
    /// </summary>
    public ValidNameSpecification ValidNameSpecification { get; set; } //👈

    /// <summary>
    /// The person's first name
    /// </summary>
    public string FirstName
    {
        get => _FirstName; 
        set
        {
            var check = ValidNameSpecification?.IsSatisfiedBy(value); //👈
            if (check?.HasFailed == true)
            {
                throw check.FailureException;
            }
            _FirstName = value;
        }
    }

    /// <summary>
    /// The person's last name
    /// </summary>
    public string LastName
    {
        get => _LastName; set
        {
            var check = ValidNameSpecification?.IsSatisfiedBy(value); //👈
            if (check?.HasFailed == true)
            {
                throw check.FailureException;
            }
            _LastName = value;
        }
    }

    ...
}

When you run the prototype again, the domain rule will execute at run-time. In the UI, the errors will appear like so:

Clone this wiki locally