liveBook · Manning

RegularExpression attribute

As explained in Building Web APIs with ASP.NET Core

A regular expression attribute is a .NET validation attribute that accepts an input value only when it matches a specified regular expression.

The RegularExpression attribute validates an input value during ASP.NET Core model binding. It accepts the value when it matches a specified regular expression, avoiding a separate manual check in the action method. section 6.1.2 section 6.1.3

For the board-game API, sortOrder must contain an allowed direction before dynamic sorting uses it. The pattern ASC|DESC expresses the two accepted alternatives. section 6.1.3

Validate sortOrder at the endpoint boundary

Add the attribute directly to the action parameter: [RegularExpression("ASC|DESC")] string? sortOrder = "ASC". ASP.NET Core applies the regular-expression check while binding the request, before the action uses sortOrder. section 6.1.3

public async Task<RestDTO<BoardGame[]>> Get(
  int pageIndex = 0,
  [Range(1, 100)] int pageSize = 10,
  string? sortColumn = "Name",
[RegularExpression("ASC|DESC")] string? sortOrder = "ASC",
  string? filterQuery = null)

Shows the RegularExpression attribute applied alongside Range validation in the board-game GET endpoint. section 6.1.3

The attribute uses the .NET regular-expression engine from System.Text.RegularExpressions. Internally, it calls Regex.IsMatch to determine whether the supplied pattern matches the input string. section 6.1.3

Prefer this declarative validator when a pattern expresses the rule clearly. A custom validation attribute remains an alternative when the rule needs behavior beyond a regular expression. section 6.1.3

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains attribute usage, pattern alternatives, and Regex.IsMatch internals without developing regular-expression syntax broadly.
Examples
Uses the board-game API's sortOrder parameter with the ASC|DESC pattern.
What it assumes
Assumes familiarity with ASP.NET Core action parameters and introduces the attribute's regular-expression validation role.
What you can do after
Apply it to constrain a model-bound string parameter with a regular-expression pattern.
How it connects
Connects data annotations with ASP.NET Core model binding, regular expressions, dynamic LINQ, and injection risks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.