2

In my web api 2 Controller i have a Create method that contains the following logic:

if (((assignment.type).ToLower() != "individual" && (assignment.type).ToLower() != "staff")) {
  return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The Assignment Type 
  must be either 'individual' or 'staff'");
  }

I am using model state validation. Is it possible to assign a regular expression to a property to eliminate the need to do the checking in the controller? If so, what would that reg ex look like to return valid only if the exact string (case insensitive) of "individual" or "staff" is passed by the user of the api?

pgtips
  • 1,328
  • 6
  • 24
  • 43

2 Answers2

3

Thanks to some guidance in the comments, I ended up with this, which works well:

[RegularExpression(@"^(?i)(individual|staff)$", ErrorMessage="...")]
public string type { get; set; }
pgtips
  • 1,328
  • 6
  • 24
  • 43
0

If you want a Regex than use something like

new Regex(@"^(individual|staff)$", RegexOptions.IgnoreCase)

But, I would recommend to create an enum with corresponding values and make your model property of that enum.

Denis Shulepov
  • 381
  • 1
  • 6
  • So the property would look like this. Any way to make it case insensitive? [RegularExpression("^(individual|staff)$"] public string type { get; set; } – pgtips Sep 10 '14 at 17:04
  • Check out this answer http://stackoverflow.com/questions/4218836/regularexpressionattribute-how-to-make-it-not-case-sensitive-for-client-side-v – Denis Shulepov Sep 13 '14 at 11:30