前面两节分别谈了用验证属性和分部类方法来验证字段,这节仍然讲讲用验证属性来验证,不过这节讲的验证属性不是系统自带的,而是我们自己写的。
using System;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;
namespace DynamicData
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
sealed public class CustomAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
bool result = true;
string str = Convert.ToString(value);
if (str.Length < 3 || str.Length > 20)
{
result = false;
}
return result;
}
}
[MetadataType(typeof(CompaniesMetadata))]
partial class Companies
{
}
partial class CompaniesMetadata
{
[CustomAttribute(ErrorMessage="Title 的长度是 3-20。")]
public object Title;
}
}
自定义属性的语法等不是动态数据的内容,这里就不再叙述了。