在一般的自定义验证特性中,我们通过继承ValidationAttribute,实现IClientValidatable,只能完成对某个属性的自定义验证。
使用IValidatableObject可以完成Model级别的验证。
□ 实现IValidatableObject接口的Model
public class RegisterModel : IValidatableObject
{
public int RegisterCount{get;set;}
public int Qutoa{get;set;}
//实现IValidatableObject接口方法,实现自定义验证
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (RegisterCount > Quota)
{
results.Add(new ValidationResult("报名人数已经超过名额限制", new string[] { "RegisterCount" }));
}
if (RegisterCount>3)
{
results.Add(new ValidationResult("单次最多报名三位学员", new string[] { "RegisterCount" }));
}
return results;
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
可见,在Model级别就自定义了验证规则。