Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API single string parameter validation using validation attributes

I know that you can use Validation attributes on a model to validate it like so:

public class CommunicationQuery
{
    [RegularExpression("[0-9]{0,10}", ErrorMessage = "Please enter a valid policy number")]
    public string PolicyId { get; set; }
    [RegularExpression("[0-9]{0,10}", ErrorMessage = "Please enter a valid member number")]
    public string MemberId { get; set; }
}

public IEnumerable<Communication> Get([FromUri]CommunicationQuery documentQuery)
{

}

But is it possible to validate a single string using validation attributes such as this?

public async Task<HttpResponseMessage> Get([RegularExpression("[0-9]{0,10}")]string id)
{

}

This didn't seem to work. The only ways I've been able to do this was to either create a wrapper object and use [FromUri], use a custom ActionFilterAttribute on the action itself or to manually validate the parameter in the controller action using a regular expression.

like image 885
Wayne Ellery Avatar asked Feb 26 '15 06:02

Wayne Ellery


1 Answers

If you're using Attribute Routing to manage your paths coming into your controllers, you can always do something like this:

[Route("{Id:regex([0-9]{0,10})}")]
public async Task<HttpResponseMessage> Get(string id)
{

}

There are various route contraints, as documented on the Attribute Routing overview documentation.

It does raise the question as to why you're accepting a numeric string of length 10 as your id. you'll have to be careful when parsing it into an int that it doesn't exceed 2,147,483,647, as that's the maximum size for a default integer.

like image 83
Yannick Meeus Avatar answered Sep 27 '22 18:09

Yannick Meeus