MVC3 Class Validation Attributes

I am creating a website for a silent auction. My class has a CurrentBidAmount property and a RecommendedBidAmount property. The recommended BidBimAmount value is the current bid amount plus the current minimum bid increment. (Thus, the current rate is 10 US dollars, and the rate increment is 5 US dollars, then the proposed rate is 15 US dollars). When a bidder enters a new bid value, I want to verify that the new value is at least the same as the proposed BibAmount or greater.

I want to apply this at the class level. The problem is that I'm not sure what validation attribute tags are and cannot find them on Google. I have to use the wrong search terms, however, I cannot find them.

The [Compare] tag is close, but it does a verbatim comparison. I need to compare one property with another and make sure that it is equal to or greater than another property.

Can someone point me in the right direction?

+3
source share
1 answer

You can create your own validation attribute and simply override its method IsValid:

    [AttributeUsage(AttributeTargets.Class)]
    public class BidCompareAttribute : ValidationAttribute
    {
        public string CurrentBidPropertyName { get; set; }
        public string MinBidIncrementPropertyName { get; set; }

        public override bool IsValid(object value)
        {
            var properties = TypeDescriptor.GetProperties(value);
            var minBidIncrement = properties.Find("MinBidIncrement", true).GetValue(value) as IComparable;
            var currentBid = properties.Find("CurrentBid", true).GetValue(value) as IComparable;
            return currentBid.CompareTo(minBidIncrement) >= 0;
        }
    }

What is it used for:

    [BidCompare(CurrentBidPropertyName = "CurrentBid", 
                MinBidIncrementPropertyName = "MinBidIncrement")]
    public class BidModel
    {
        public int CurrentBid { get; set; }    
        public int MinBidIncrement { get; set; }
    }
+2
source

All Articles