Ok so maybe you read this post and you’re thinking to yourself, “I wonder if Diet Dr. Pepper really does taste like regular Dr. Pepper” which of course is silly because the ads clearly say it does. Now you should be asking yourself, “How do I check if two properties have the same value on a class with annotation when the property level ones only can check the one property’s value?” Kind of wordy way of asking that, but I get what you’re asking. Better yet, like usual, I have an answer.
Now what I can swear is that I was no where near the Baxter Building between 1-3 am on Saturday the 15th. I was in fact I was sleeping and have 20 witnesses that can testify. What I can’t swear is this is the best way to go about it but it seems to work AND make sense. It’s not common for me to come up with solutions that do both.
[AttributeUsage(AttributeTargets.Class)] public class PropertiesMatchAttribute : ValidationAttribute { public String FirstPropertyName { get; set; } public String SecondPropertyName { get; set; } //Constructor to take in the property names that are supposed to be checked public PropertiesMatchAttribute(String firstPropertyName, String secondPropertyName ) { FirstPropertyName = firstPropertyName; SecondPropertyName = secondPropertyName ; } public override Boolean IsValid(Object value) { Type objectType = value.GetType(); //Get the property info for the object passed in. This is the class the attribute is // attached to //I would suggest caching this part... at least the PropertyInfo[] PropertyInfo[] neededProperties = objectType.GetProperties() .Where(propertyInfo => propertyInfo.Name == FirstPropertyName || propertyInfo.Name == SecondPropertyName) .ToArray(); if(neededProperties.Count() != 2) { throw new ApplicationException("PropertiesMatchAttribute error on " + objectType.Name); } Boolean isValid = true; //Convert both values to string and compare... Probably could be done better than this // but let's not get bogged down with how dumb I am. We should be concerned about // dumb you are, jerkface. if(!Convert.ToString(neededProperties[0].GetValue(value, null)).Equals(Convert.ToString(neededProperties[1].GetValue(value, null)))) { isValid = false; } return isValid; } } }
And then the use:
[PropertiesMatchAttribute("Password", "ConfirmPassword", ErrorMessage = "Match the passwords, dumb--s.")] public class UserCreateModel { public String ConfirmPassword{ get; set; } public String Password { get; set; } }
Wasn’t so hard was it? Normally this would be the part where I degrade you for being bumb because you didn’t figure this out but I’m above that now. I guess it must be the holiday season or that I’ve been told by the board that I should be more gentle with my readers. Guess some were crying after reading some of my posts. Yeah whatever. Bunch of [Removed by Andre].