dco*_*bus 1 customvalidator asp.net-mvc-2
我被引导到一篇非常好的文章,该文章展示了如何从头到尾创建自定义验证器.我唯一的问题是这只适用于单个字段:http: //haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
如果我需要在模型中验证2个或更多属性,该怎么办?如何将整个模型传递给Validator?
注意:要清楚,我真的不想在回发后验证整个模型......这会破坏这种方法的目的.
您需要使用自定义验证属性并使用它来装饰模型,而不是单个属性:
[AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class MyCustomValidatorAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
// value here will be the model instance you could cast
// and validate properties
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
然后用它装饰你的模型:
[MyCustomValidator]
public class MyViewModel
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
作为执行验证的数据注释的替代方法,我强烈建议您使用FluentValidation.NET.它还与ASP.NET MVC有很好的集成.
| 归档时间: |
|
| 查看次数: |
1525 次 |
| 最近记录: |