Home > other >  Regex Constraint in Attribute parameter throwing error
Regex Constraint in Attribute parameter throwing error

Time:02-23

I think I am doing this constraint wrong. I want the year to be 4 digits, the month to be 2 digits, and the month to range from 1 to 12:

[Route("projects/released/{year:regex(\\d{4})}/{month:regex(\\d{2}):range(1,12)}")]

I get the following error in rider:

Route parameter constraint 'regex(\d{2' not resolved

I'm running .NET 6 ASP.NET Core MVC

CodePudding user response:

Use the following:

[Route("projects/released/{year:regex(^\\d{{4}}$)}/{month:regex(^\\d{{2}}$):range(1,12)}")]
public IActionResult Index(string year, string month)
{
    // your code...
}

See detailed description in the documentation: Regular expressions in constraints

Pay attention: to escape routing parameter delimiter characters {, }, [, ], double the characters in the expression, for example, {{, }}, [[, ]].

  • Related