Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 class validation attributes

I am creating a site for a silent auction. My class has a CurrentBidAmount property, and a SuggestedBidAmount property. The SuggestedBidAmount is basically the current bid amount plus the current minimum bid increment. (So the current bid is $10, and the bid increment is $5, then the suggested bid is $15). When the bidder enters a new bid value, I want to validate that the new value is at least as much as the SuggestedBidAmount or greater.

I want to enforce this at the class level. The problem is, I'm not sure of what the validation attribute tags are, and can't seem to find them on Google. I must be using the wrong search terms, nonetheless, I can't find them.

The [Compare] tag is close, but that does a verbatim compare. I basically need to compare one property against another, and verify that it is equal to or greater than the other property.

Can anyone please point me in the right direction?

like image 422
Todd Davis Avatar asked Jan 29 '26 07:01

Todd Davis


1 Answers

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

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

Than use it like this:

    [BidCompare(CurrentBidPropertyName = "CurrentBid", 
                MinBidIncrementPropertyName = "MinBidIncrement")]
    public class BidModel
    {
        public int CurrentBid { get; set; }    
        public int MinBidIncrement { get; set; }
    }
like image 121
frennky Avatar answered Jan 30 '26 22:01

frennky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!