Property Matching With Data Annotations

I found myself needing to compare two properties on a view model when developing a new ASP.NET MVC 2.0 site today. My initial thoughts were I would check the two properties for equality by making a call to my business logic assembly.

I wondered if it would be possible to compare two properties using data annotations. Usually you place the data annotations attribute on a property to validate the data in some way. I quickly knocked up a custom ValdationAttribute that could be placed on a class that checks for equality between two properties of the class. It checks both type and value equality.

using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace Model.CustomAnnotations
{
    [AttributeUsage(AttributeTargets.Class)]
    public class MatchAttribute : ValidationAttribute
    {
        public String SourceProperty { get; set; }
        public String MatchProperty { get; set; }

        public MatchAttribute(string source, string match)
        {
            SourceProperty = source;
            MatchProperty = match;
        }

        public override Boolean IsValid(Object value)
        {
            Type objectType = value.GetType();

            PropertyInfo[] properties = objectType.GetProperties();

            object sourceValue = new object();
            object matchValue = new object();

            Type sourceType = null;
            Type matchType = null;

            int counter = 0;

            foreach (PropertyInfo propertyInfo in properties)
            {
                if (propertyInfo.Name == SourceProperty || propertyInfo.Name == MatchProperty)
                {
                    if (counter == 0)
                    {
                        sourceValue = propertyInfo.GetValue(value, null);
                        sourceType = propertyInfo.GetValue(value, null).GetType();
                    }
                    if (counter == 1)
                    {
                        matchValue = propertyInfo.GetValue(value, null);
                        matchType = propertyInfo.GetValue(value, null).GetType();
                    }
                    counter++;
                    if (counter == 2)
                    {
                        break;
                    }
                }
            }

            if (sourceType != null && matchType != null)
            {
                if (Convert.ChangeType(sourceValue, sourceType) == Convert.ChangeType(matchValue, matchType))
                    return true;
            }
            return false;
        }
    }
}

Here is how the attribute is placed on a class. The attribute takes two values which are the names of the properties you need to match.

    [Match("Email", "EmailConfirmation", ErrorMessage = "Emails must match")]
    public class PersonViewModel
    {
        public int PersonId { get; set; }
        [Required]
        public string Firstname { get; set; }
        [Required]
        public string Lastname { get; set; }
        [Required]
        public string Email { get; set; }
        [Required]
        public string EmailConfirmation { get; set; }
    }

This then bubbles up to the UI. If you are using MVC 2.0 this will work out of the box as the default model binder supports data annotations.

Pretty straight forward but very useful! You can download the code here to see it working end to end. You will need MVC 2.0 RC installed as well as Visual Studio Standard Edition or above.

Twitter Twitter Twitter Twitter Twitter
January 9, 2010 19:04 by DanWatson

Comments

January 5. 2010 16:50

trackback

Property Matching With Data Annotations

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com

January 20. 2010 14:44

Caretaker Pools Parts

This article would be one of the ASP.net I used to know, thanks for sharing it with us. Hope you could make more articles that are useful and very interesting to everyone. Thanks a lot! Have a nice day!

Caretaker Pools Parts

January 29. 2010 04:01

buenos aires travel guide

It could be great if we can comprare properties!

buenos aires travel guide

March 4. 2010 06:02

Fred Perry

I do learn a lot from this blog.

Fred Perry

March 6. 2010 05:47

Swarovski bead suppliers

The code is very useful, but taking me a bit of time to get to grips with as ASP is fairly new to me.

Swarovski bead suppliers

April 9. 2010 17:51

u4873

Wow I am so satisfied that I have found this your post. I have been searching for some information about the Property Matching with data annotations for almost an hour and accidentally I have found this your article. As I see you have done a great research about this subject and this post is really full of various useful information indeed. Some parts of your post was a little bit difficult for me  to understand but it does not matter now. Thanks a lot one more time for the informative entry and I will be waiting for more such great posts like this one in the future too.

u4873

April 12. 2010 00:57

career planning

Comparing two properties using data annotation is a new thing for me, as I consider using annotation attribute on a single property to validate the data. So I am happy to find this new way of comparing the two properties using ValidationAttribute in data annotations. It becomes more easier through coding. Thanks

career planning

April 13. 2010 18:23

decorating games

Superb blog post. I've bookmarked it already.

decorating games

April 14. 2010 22:44

LPN To RN

After reading your comparison between two properties using data annotation, I was perplex. But the coding really help me understand that what you are talking about. I hardly think out of the box, so for me this type of experiments are very hard to understand. Anyways I am glad to read your article.

LPN To RN

April 15. 2010 21:52

business coupon

How long have you been in this field? You seem to know a lot more than I do, I’d love to know your sources!

business coupon

April 15. 2010 21:54

business opportunities

Why didn’t I find this post earlier? Keep up the good work!

business opportunities

April 17. 2010 01:28

image consultant melbourne

http://www.imagegroup.com.au/
Useful info. Hope to see more good posts in the future.

image consultant melbourne

Comments are closed