views:

394

answers:

1

I have a complete validation on an obeject and am trying to figure out the best way to handle it.

Given the following class:

public class LetterResponse {
 public Guid Id {get;set;}
 public bool SendBlankCart {get;set;}
 public string ToName {get;set;}
 public string ToAddress {get;set;}
}

I want to use a dataannotation and xval in order to validate the class before I persist it, but I have complex validation that requires more than one property.

Pseudo:

if SendBlankCart {
 - no validation on ToName, ToAddress 
} else {
 ToName - required.
 ToAddress - required. 
}

I would like to annotate like this:

[LetterResponseValidator]
public class LetterResponse {
 public Guid Id {get;set;}
 public bool SendBlankCart {get;set;}
 public string ToName {get;set;}
 public string ToAddress {get;set;}
}

and have a validation rule like this:

public class LetterResponseValidator : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value.GetType() == typeof(LetterResponse))
            {
                var letterResponse = (letterResponse) value;
                if (letterResponse.SendBlankCard)
                {
                    return true;
                } else
                {
                    if (string.IsNullOrEmpty(letterResponse.FromDisplayName) || string.IsNullOrEmpty(letterResponse.ToAddress1))
                    {
                        return false;
                    }
                    return true;
                }

            }
            return false;
        }
    }

I am expecting the parameter to be my instance of the LetterResponse class, but it never gets called on my validation runner?

Does anyone know a way to handle this?

Thanks,

Hal

+2  A: 

I don't think this has to do with the fact that you have a class-level validator. To exclude any connection, try applying a dummy required validator to "ToName" and see if the validator is called or not.

If it is being called, then let me know, if it's not, then you should check if you have overriden your standard modelbinder with the DataAnnotationsModelBinder in your Global.asax.cs file:

ModelBinders.Binders.DefaultBinder = new DataAnnotationsModelBinder();

For more details on this and fully working demo project, read this blog article about client-side validation.

Adrian Grigore
Yep - turns out my DataAnnotation runner method was only checking properties, not attributes on the class level. Thanks, Hal
Hal
do you know where i can find a DataAnnotationsModelBinder that is gonna work with System.ComponentModel.DataAnnotations v 3.5
Omu
The regular one does work with .NET version 3.5, apart from a bug which I described in the blog article linked above. The article also shows how to fix the bug.
Adrian Grigore