Tuesday 15 February 2011

c# - Web API custom validation to check string against list of approved values -


I want to validate an input on a Web API REST command. I want to do something like this down to state , being decorated with the attribute which limits the valid values ​​of the parameter.

  public square item {/ ... I want the state to be just "new", "used", or "unknown" [required] [Valid values ​​({ "New", "used", "unknown"})] get public string state { Set; } [Required] Public string description {get; Set; } ...}   

Is there any way to do this without going against the web API's grain? Ideally the Ruby on Rails will be similar.

Get a custom verification attribute from verification entry and IsValid override the member function.

  public class Valid Validate: ValidationAttribute {string [] _args; Public ValidValuesAttribute (parameter string [] args) {_args = args; } Protected Override Validation Result IsValid (Object Value, Validation Contact Validation Verification) {If (_args.Contains (string) value)) Return Validation Results. Success; New verification returns return ("Invalid value."); }}   

You can

  [Valid values ​​("new", "used", "unknown")]  < / Pre> 

The above code has not been compiled or tested.

No comments:

Post a Comment