我正在尝试验证我拥有的模型上的属性。此属性不是必需的,因此如果它的无效 MVC 似乎忽略它。我什至创建了一个自定义 ValidationAttribute,但没有任何效果。
public class NumberWang : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null)
return true;
int g;
if (int.TryParse(value.ToString(), out g))
{
if (g >= 0)
return true;
}
return false;
}
}
public class MyModel
{
[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
[NumberWang(ErrorMessage = "That's NumberWang!")]
public int? category_id { get; set; }
/* there are other properties of course, but I've omitted them for simplicity */
public void Validate()
{
Validator.TryValidateProperty(this.category_id,
new ValidationContext(this, null, null) { MemberName = "category_id" },
this.validation_results);
}
}
如果我将值“abc”作为 category_id 传递给该模型,则它验证得很好。我究竟做错了什么?