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.
You can use the Validate() method of the ApiController class to manually validate the model and set the ModelState.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With