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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…