看看這個post on SO。基本上,通過示例propertiesMustMatch驗證來了解如何將數據註釋與多個屬性一起使用。這是什麼新的代碼可能是一個快速刺(注意,可能不是100%的上限語法正確,半成品)
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class RequiredMedicalNum: ValidationAttribute
{
private const string _defaultErrorMessage = "{0} is required when certified is true";
private readonly object _typeId = new object();
public RequiredMedicalNum(string medicalNum, string Certified)
: base(_defaultErrorMessage)
{
_medicalNum = medicalNum;
_certified= Certified;
}
public string _medicalNum
{
get;
private set;
}
public string _certified
{
get;
private set;
}
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
_medicalNum, _certified);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object medicalNum = properties.Find(_medicalNum, true /* ignoreCase */).GetValue(value);
object certified= properties.Find(_certified, true /* ignoreCase */).GetValue(value);
if(certified == 1){
Return String.IsNullOrEmpty(medicalNum);
}
}
}
感謝湯米,我會看一看的鏈接,我很欣賞你的代碼。今天下午會嘗試它,並從它的外觀,應該是我正在尋找的。 – 2010-07-15 18:42:16