如何在MVC中开发自定义验证规则?即我的模型中有很多十进制属性,我想对所有这些属性进行范围验证,而不使用每个数据注释。
答案 0 :(得分:1)
您可以通过实现IValidatableObject来为整个模型添加验证,例如:
public class MyModel: IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (MyProperty > 100 || MyProperty < 1)
yield return new ValidationResult("MyProperty is out of range (1..100)", new [] { "MyProperty" });
...
}
}
Here's a resource that has a more elaborate example.
如果您想自动覆盖所有小数属性,可以执行以下操作:
public abstract class MyValidatableBaseModel: IValidatableObject
{
protected abstract virtual Type GetSubClassType();
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var decimalProperties = GetSubClassType().GetProperties().Where(p => p.PropertyType == typeof(decimal));
foreach (var decimalProperty in decimalProperties)
{
var decimalValue = (decimal)decimalProperty.GetValue(this, null);
var propertyName = decimalProperty.Name;
//do validation here and use yield return new ValidationResult
}
}
}
public class MyModel : MyValidatableBaseModel
{
protected override Type GetSubClassType()
{
return GetType();
}
}
任何继承自MyValidatableBaseModel(在示例中为MyModel)并覆盖GetSubClassType以返回其自己的类型的模型将具有对十进制属性的自动验证