views:

4

answers:

0

I'm just getting to grips with custom validation attributes, and I'm trying to write a custom validation attirbute which will be placed at class level to validate against multiple properties of my model.

I can access all properties on my model, and I want to be able to check for multiple conditions in my IsValid overload, and report on them, having different error messages as follows (simplistic example).

public override bool IsValid(object value)
    {
        var model = (MyObject) value;

        //if this value is set, I don't want to do anything other checks
        if (model.Prop3)
        {
            return true;
        }

        if (model.Prop1 == "blah" && model.Prop2 == 1)
        {
            ErrorMessage = "you can't enter blah if prop 2 equals 1";
            return false;
        }

        if(model.Prop1 == "blah blah" && model.Prop2 == 2)
        {
            ErrorMessage = "you can't enter blah blah if prop 2 equals 2";
            return false;
        }


        return true;
    }

But when I do this I get an exception on the first time ErrorMessage is referenced "Cannot set property more than once.

Now I could split up my custom attribute into multiple custom attributes, but hoped there would be a way to do it in one, otherwise, I'll be repeating my "catch all" in each

//if this value is set, I don't want to do anything other checks
        if (model.Prop3)
        {
            return true;
        }

I've had a search already, but couldn't find anything, so apologies if I am missing anything obvious.

thanks in advance!