IC Improve Code Recipes

Recipe 8.2 · C#

DataAnnotations That Actually Run

Problem

You decorate a request class with [Required] and [StringLength], and in ASP.NET Core MVC the framework checks them for you. Then the same class is used in a console importer, a background job, or a minimal API endpoint that does not run model validation, and the attributes quietly do nothing. Cross-field rules, such as "end date after start date," are bolted on somewhere else.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
var results = new List<ValidationResult>();
var ctx = new ValidationContext(model, null, null);
bool ok = Validator.TryValidateObject(model, ctx, results);
if (!ok)
{
    lblError.Text = results[0].ErrorMessage;
}

This looks right and is one of the most common validation bugs I find. Without the fourth argument, validateAllProperties, TryValidateObject only evaluates [Required]. [Range], [StringLength], [EmailAddress] and every custom attribute are skipped. Showing only the first error is a separate annoyance for the user.

The improved recipe

The request class keeps its attributes, adds one custom attribute and implements IValidatableObject for the cross-field rule. A small static helper runs everything and returns the errors grouped by property, in the same shape ASP.NET Core uses for ValidationProblemDetails.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace ImproveCode.Validation;

[AttributeUsage(AttributeTargets.Property)]
public sealed class NotInPastAttribute : ValidationAttribute
{
    public NotInPastAttribute()
        : base("{0} cannot be in the past.")
    {
    }

    protected override ValidationResult? IsValid(
        object? value, ValidationContext context)
    {
        if (value is not DateOnly date)
        {
            return ValidationResult.Success;
        }

        var clock = context.GetService(typeof(TimeProvider))
            as TimeProvider ?? TimeProvider.System;
        DateOnly today =
            DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);

        return date >= today
            ? ValidationResult.Success
            : new ValidationResult(
                FormatErrorMessage(context.DisplayName),
                [context.MemberName ?? context.DisplayName]);
    }
}

public sealed class ContractRequest : IValidatableObject
{
    [Required, StringLength(100, MinimumLength = 2)]
    public string CustomerName { get; set; } = "";

    [Required, EmailAddress, StringLength(254)]
    public string ContactEmail { get; set; } = "";

    [Range(1, 500)]
    public int Seats { get; set; }

    [Required, AllowedValues("USD", "EUR", "GBP")]
    public string Currency { get; set; } = "USD";

    [NotInPast]
    public DateOnly StartDate { get; set; }

    public DateOnly EndDate { get; set; }

    public IEnumerable<ValidationResult> Validate(
        ValidationContext validationContext)
    {
        if (EndDate <= StartDate)
        {
            yield return new ValidationResult(
                "End date must be after the start date.",
                [nameof(EndDate)]);
        }
    }
}

public static class ModelValidator
{
    public static IReadOnlyDictionary<string, string[]> Validate(
        object model, IServiceProvider? services = null)
    {
        ArgumentNullException.ThrowIfNull(model);

        var context = new ValidationContext(model, services, null);
        var results = new List<ValidationResult>();
        Validator.TryValidateObject(
            model, context, results, validateAllProperties: true);

        return results
            .SelectMany(r => MembersOf(r)
                .Select(m => (Member: m, Message: r.ErrorMessage)))
            .GroupBy(x => x.Member)
            .ToDictionary(
                g => g.Key,
                g => g.Select(x => x.Message ?? "Invalid value.")
                      .Distinct()
                      .ToArray());
    }

    private static IEnumerable<string> MembersOf(ValidationResult r)
    {
        var members = r.MemberNames.ToList();
        return members.Count == 0 ? [""] : members;
    }
}

How it works

ModelValidator.Validate always passes validateAllProperties: true, which is the one-line fix to the bug above. Errors without a member name, which happen when a class-level rule forgets to name one, go under an empty key so they are not lost. The dictionary drops straight into Results.ValidationProblem(errors) in a minimal API, or into a list on a console importer's error report.

AllowedValues is new in .NET 8, along with DeniedValues, Length (minimum and maximum for strings and collections) and Base64String. Range also gained MinimumIsExclusive and MaximumIsExclusive. Before these, every team wrote its own [InList] attribute.

The custom NotInPast attribute shows two habits worth copying. It returns success for values it does not understand, so it combines with [Required] instead of duplicating it. And it asks the ValidationContext for a TimeProvider, falling back to the system clock. Pass a service provider that holds a fake TimeProvider and your tests stop depending on today's date.

IValidatableObject.Validate handles rules that span properties. The framework only calls it when every property attribute has passed, so you can assume the individual fields are well formed inside it.

Variations and pitfalls

  • Nested objects are not validated. TryValidateObject does not walk into child objects or collections. Either validate them separately and prefix the keys (Lines[2].Quantity), or use the validator in Recipe 8.3, which makes nesting explicit.
  • [EmailAddress] is permissive on purpose. It checks for one @ with something on each side. That is fine. The only real proof of an e-mail address is a message that arrives. Do not paste in a 400-character regular expression.
  • [Required] on a non-nullable int does nothing. The value is always present, 0 by default. Use [Range], or make the property int? with [Required] if "not supplied" must be detectable.
  • Minimal APIs. ASP.NET Core 10 adds built-in validation for minimal APIs through AddValidation(). On .NET 8 and 9, call ModelValidator.Validate in an endpoint filter so every endpoint gets the same behavior.
  • Options classes. The same attributes validate configuration through ValidateDataAnnotations() and ValidateOnStart(), covered in Chapter 6.