有没有人能帮我做一下System.ComponentModel.dataAnnotations.CustomValidation.的全面展示
这是我的头像
我有EventMetadata & EventAttributeMetadata课程。在EventMetadata中,我有Startdate和Enddate属性&在EventAttributeMetadata中,我有HoldOutdate属性。我想对HoldOutdate属性执行以下验证。“延迟日期应在事件开始日期和结束日期之间”。这应该使用System.ComponentModel.dataAnnotations命名空间。
发布于 2010-10-21 19:57:54
此示例位于创建一个非空的默认mvc应用程序时创建的AccountModel中,并根据需要对其进行修改和使用。
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class PropertiesMustMatchAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";
private readonly object _typeId = new object();
public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
: base(_defaultErrorMessage)
{
OriginalProperty = originalProperty;
ConfirmProperty = confirmProperty;
}
public string ConfirmProperty { get; private set; }
public string OriginalProperty { get; private set; }
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, ConfirmProperty);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
return Object.Equals(originalValue, confirmValue);
}
}https://stackoverflow.com/questions/3986689
复制相似问题