簡體   English   中英

自定義驗證屬性,用於將my屬性的值與模型類中的另一個屬性值進行比較

[英]Custom validation attribute that compares the value of my property with another property's value in my model class

我想創建一個自定義驗證屬性,我想在其中將my屬性的值與我的模型類中的另一個屬性值進行比較。 例如我在我的模型類中:

...    
public string SourceCity { get; set; }
public string DestinationCity { get; set; }

我想創建一個自定義屬性來像這樣使用它:

[Custom("SourceCity", ErrorMessage = "the source and destination should not be equal")]
public string DestinationCity { get; set; }
//this wil lcompare SourceCity with DestinationCity

我要怎么去那兒?

以下是獲取其他屬性值的方法:

public class CustomAttribute : ValidationAttribute
{
    private readonly string _other;
    public CustomAttribute(string other)
    {
        _other = other;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_other);
        if (property == null)
        {
            return new ValidationResult(
                string.Format("Unknown property: {0}", _other)
            );
        }
        var otherValue = property.GetValue(validationContext.ObjectInstance, null);

        // at this stage you have "value" and "otherValue" pointing
        // to the value of the property on which this attribute
        // is applied and the value of the other property respectively
        // => you could do some checks
        if (!object.Equals(value, otherValue))
        {
            // here we are verifying whether the 2 values are equal
            // but you could do any custom validation you like
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }
        return null;
    }
}

請看下面我的例子:

Model類實現了INotifyPropertyChanged

public class ModelClass : INotifyPropertyChanged
{
    private string destinationCity;

    public string SourceCity { get; set; }

    public ModelClass()
    {
        PropertyChanged += CustomAttribute.ThrowIfNotEquals;
    }

    [Custom("SourceCity", ErrorMessage = "the source and destination should not be equal")]
    public string DestinationCity
    {
        get
        {
            return this.destinationCity;
        }
        set
        {
            if (value != this.destinationCity)
            {
                this.destinationCity = value;
                NotifyPropertyChanged("DestinationCity");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void NotifyPropertyChanged(string info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

屬性類還包含事件hendler。

internal sealed class CustomAttribute : Attribute
{
    public CustomAttribute(string propertyName)
    {
        PropertyName = propertyName;
    }

    public string PropertyName { get; set; }

    public string ErrorMessage { get; set; }

    public static void ThrowIfNotEquals(object obj, PropertyChangedEventArgs eventArgs)
    {
        Type type = obj.GetType();

        var changedProperty = type.GetProperty(eventArgs.PropertyName);

        var attribute = (CustomAttribute)changedProperty
            .GetCustomAttributes(typeof(CustomAttribute), false)
            .FirstOrDefault();

        var valueToCompare = type.GetProperty(attribute.PropertyName).GetValue(obj, null);

        if (!valueToCompare.Equals(changedProperty.GetValue(obj, null)))
            throw new Exception("the source and destination should not be equal");
    }
}

用法

    var test = new ModelClass();
    test.SourceCity = "1";
    // Everything is ok
    test.DestinationCity = "1";
    // throws exception
    test.DestinationCity ="2";

為了簡化代碼,我決定省略驗證。

執行此操作的最佳方法是使用IValidatableObject。 請參閱http://msdn.microsoft.com/en-us/data/gg193959.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM