I am creating a site for a silent auction. My class has a CurrentBidAmount pro开发者_运维百科perty, 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?
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; }
}
精彩评论