Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'd like to validate an input on a Web API REST command. I'd like it to work something like State below being decorated with an attribute that limits the valid values for the parameter.

public class Item {
    ...

    // I want State to only be one of "New", "Used", or "Unknown"
    [Required]
    [ValidValues({"New", "Used", "Unknown"})]
    public string State { get; set; }

    [Required]
    public string Description { get; set; }

    ...
}

Is there a way to do this without going against the grain of Web API. Ideally the approach would be similar to Ruby on Rails' custom validation.

like image 319
Paul Oliver Avatar asked Jun 21 '13 20:06

Paul Oliver


People also ask

Which of the following is used to check the validity of the model in Web API?

You can use the Validate() method of the ApiController class to manually validate the model and set the ModelState.


1 Answers

Create a custom validation attribute derived from ValidationAttribute and override the IsValid member function.

public class ValidValuesAttribute: ValidationAttribute
{
  string[] _args;

  public ValidValuesAttribute(params string[] args)
  {
    _args = args;
  }

  protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  {
    if (_args.Contains((string)value))
      return ValidationResult.Success;
    return new ValidationResult("Invalid value.");
  }
}

Then you can do

[ValidValues("New", "Used", "Unknown")]

The above code has not been compiled or tested.

like image 193
Matt Houser Avatar answered Oct 13 '22 00:10

Matt Houser