Introduction
A previous blog post discussed how to enable and use the basics of attribute routing within an MVC application. The blog also touched upon URI parameter constraints and the out-of-the-box constraints with MVC 5.
The general syntax for imposing constraint is {parameter:constraint}
Below is a list of constraints with examples:
Constraint | Description | Example |
alpha | Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z) | {x:alpha} |
bool | Matches a Boolean value. | {x:bool} |
datetime | Matches a DateTime value. | {x:datetime} |
decimal | Matches a decimal value. | {x:decimal} |
double | Matches a 64-bit floating-point value. | {x:double} |
float | Matches a 32-bit floating-point value. | {x:float} |
guid | Matches a GUID value. | {x:guid} |
int | Matches a 32-bit integer value. | {x:int} |
length | Matches a string with the specified length or within a specified range of lengths. | {x:length(6)} {x:length(1,20)} |
long | Matches a 64-bit integer value. | {x:long} |
max | Matches an integer with a maximum value. | {x:max(10)} |
maxlength | Matches a string with a maximum length. | {x:maxlength(10)} |
min | Matches an integer with a minimum value. | {x:min(10)} |
minlength | Matches a string with a minimum length. | {x:minlength(10)} |
range | Matches an integer within a range of values. | {x:range(10,50)} |
regex | Matches a regular expression. | {x:regex(^\d{3}-\d{3}-\d{4}$)} |
How to create your own custom parameter constraint:
Values Constraint
This constraint will be used to validate a string parameter by allowing the developer to specify the allowed values passed by the parameter. You’re probably thinking why not handle validating the parameter in the controller action or mode… But if you know the static values that can be passed, why clutter up your controller or model?
First we need to create a ValuesConstraint class that will implement the IRouteConstraint interface. This interface only contains one method.
Once we have the class, we need to add an array variable for our valid parameter values and a constructor to populate variable. In the match method, we get the parameter value and validate it against the allowed values. You can set it up to be case-sensitive, however, in the example below, we’re ignoring case.
And that’s how to create a custom constraint, folks. Now we can add this to our controller action.
The syntax for imposing this constraint is {parameter:values(string[])}
Conclusion
Creating your own custom constraints can be very quick and easy. This a basic example, but can be easily modified to meet your needs and complexities.
Save
Save