Skip to content

Expo Regex Rules

SteffenBlake edited this page Sep 28, 2026 · 1 revision

Generated regex rules

Declare a regex with [GeneratedRegex] inside an Expo model to generate a validation attribute for that pattern. The attribute name is StringMatches followed by the regex member's name.

Define and apply a pattern

// CourseReference.cs
[Expo]
public sealed partial class CourseReference
{
    [IsRequired]
    [StringMatchesReferenceRegex("Use a reference such as COURSE-0042.")]
    public string? Reference { get; init; }

    [GeneratedRegex(@"^COURSE-\d{4}$", RegexOptions.CultureInvariant)]
    private static partial Regex ReferenceRegex();
}

GeneratedRegex, Regex, and RegexOptions are in System.Text.RegularExpressions. The .NET regex generator supplies ReferenceRegex; Expo generates [StringMatchesReferenceRegex] for properties in the same model.

The pattern requires COURSE- followed by four digits. The anchors make the regex check the full text. Without anchors, Regex.IsMatch can accept a matching substring.

Nulls and collections

The generated pattern rule accepts null. Add [IsRequired] for a required scalar value. An empty string fails when the pattern does not match it.

On a string collection, the generated rule checks each non-null item and reports failures at indexed pointers. Use collection rules for presence and size; see Collections.

Scope and messages

Generated regex attributes are private to the model that declares the regex. Their only optional argument is the error message. Use a Reusable custom rule when several models need one shared validation attribute.

Expo includes the pattern in Model metadata. The ASP.NET Core OpenAPI integration can publish it as a schema constraint.

Clone this wiki locally