How to create NotRequiredIfFalse

Dec 23, 2010 at 5:21 PM

Hi there, love the work you have done so far.

I was wondering how would i go about creating a attribute that will look at a dependent property and enforce that a value IS NULL if dependent is set to false?


Many thanks,


Dec 23, 2010 at 6:28 PM

How about this:


using Foolproof;

namespace MvcApplication1
    public class EnforceNullIfFalse : ContingentValidationAttribute
        static EnforceNullIfFalse() { Register.Attribute(typeof(EnforceNullIfFalse)); }

        public EnforceNullIfFalse(string dependentProperty) : base(dependentProperty) { } 

        public override bool IsValid(object value, object dependentValue, object container)
            if (!(dependentValue is bool))
                return true;

            if ((bool)dependentValue)
                return true;

            return value == null;

Dec 24, 2010 at 9:56 AM

Works very well, many thanks for taking the time to look into this for me.