Archive for September 15th, 2011

Conditional DataAnnotations in c#

This is something a bit weird, which maybe even, dare I say, a bug in the .net DataAnnotationsExtensions pack (Installable via NuGet). I decorated one of my class properties with an Email data annotation, because If the class had an email set, I wanted to ensure it was valid. I didn’t, however, decorate it with a Required attribute. However it seems the Email attribute will return false if no value is passed, ensuring that it is infact required? (Please leave a comment if there is some really obvious built in way around this!)

To get around this I created a simple “IfPresent” data annotation which you can chain another validation onto; This basically returns a true if the value is null, otherwise it will pass it on to the real ValidationAttribute to work it”s magic. It can be implemented like this;

[IfPresent(typeof(EmailAttribute), ErrorMessage = "Must be a valid email address")]
public string EmailAddress { get; set; }

The code is;

namespace Chinook.Model.ValidationAttributes
    public class IfPresent : ValidationAttribute
        private ValidationAttribute attr;

        public IfPresent(Type attr)
            this.attr = (ValidationAttribute)Activator.CreateInstance(attr); 

        public override bool IsValid(object value)
            if (value == null)
                return true;

            return attr.IsValid(value);


I absolutely love these. They came at the lace wigs are good quality, and very soft. Absolutely love these extensions. I just love this hair. Hair came on time, I waited until after hair extensions uk very full, no shedding and it is been installed for 3 weeks now and yes I jus ordered 3 more bundles. Lol. I definitely recommend this company for your bundles ladies. They are soft, hair bundles on the head for human hair wigs and I would continue to recommend them. I have thinner hair so they cover and blend nicely.