Skip to content

ValidationModulesValidation for .NET, written at build time

Declare rules with attributes or in a rules class. A source generator turns them into a validator class of plain C#, which runs under Native AOT.

A model with constraint attributes beside the validator code generated from it

Example ​

csharp
using ValidationModules.Constraints;

public sealed class SignUp
{
    [Required, EmailAddress]
    public string? Email { get; init; }

    [Required, StringLength(40, Min = 3)]
    public string? DisplayName { get; init; }

    [Range(18, 120)]
    public int Age { get; init; }
}

The generator writes SignUpValidator from these attributes. Validating new SignUp { Email = "not-an-email", DisplayName = "", Age = 12 } with it returns three errors:

FieldCodeMessage
emailemailemail is not a valid email address.
displayNamerequireddisplayName is required.
agerangeage must be between 18 and 120.

What it does ​

  • The generator checks your declarations as it reads them. An attribute on the wrong kind of member, a regular expression that does not parse, or a length whose minimum is above its maximum is a build error.
  • Each error has a field path, a stable code, a message and a severity. Code that reacts to errors can key on the code, and translations can replace the message.
  • The validators contain no reflection, so they work in trimmed and Native AOT applications.
  • Most attributes share their names with System.ComponentModel.DataAnnotations, such as [Required], [StringLength] and [Range]. Models that already use DataAnnotations attributes compile as they are.
  • Companion packages validate ASP.NET Core minimal API arguments, check options when the host starts, and supply translated messages.

Packages ​

PackageContents
ValidationModules.RuntimeAttributes, IValidatorFor<T>, results, and service registration.
ValidationModules.SourceGeneratorThe source generator and its analyzers.
ValidationModules.AspNetCoreAn endpoint filter for minimal APIs and RFC 9457 problem details.
ValidationModules.OptionsOptions validation when the host starts.
ValidationModules.MessagesMessages in German, Spanish, French, Japanese and Chinese.
ValidationModules.SourceGenerator.ImplThe generator's source, for authors of other generators.

Released under the MIT License.