开发者

System.ComponentModel.dataAnnotations.CustomValidation

开发者 https://www.devze.com 2023-01-20 23:25 出处:网络
can anyone please help me with full expmple of System.ComponentModel.dataAnnotations.CustomValidation.

can anyone please help me with full expmple of System.ComponentModel.dataAnnotations.CustomValidation.

This is my scnario

I have EventMetadata & EventAttributeMetadata class. In EventMetadata i have Startdate开发者_运维技巧 & Enddate Property & In EventAttributeMetadata i have HoldOutdate Propety. I want perform following validation for HoldOutdate property. "Holdout Date should be between event start date & end date". this should be using System.ComponentModel.dataAnnotations namespace.


This example is in the AccountModel that is created when you make a default mvc app that is not empty modify it to your need and use.

[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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消