ASP.NET MVC3 System.ComponentModel.DataAnnotations -- can an annotation determine the class it is validating?

I am using a "Extended Validation" attribute to turn on stricter validation depending on how I am editing a record.

EG: I have a Parent which has children objects.

When Editing a Child, ModelState.isValid is false, due to the parent missing, e.g a first name, because I am selecting its parent by ID only.

When I edit a Parent -- I want these fields to be required, but not when editing e.g a child and the associated parent is part of what makes up the child.

I have the following code:

public class Parent
{
    [Required]        
    public virtual int Id { get; set; }


    [ExtendedValidationRequired(typeof(Parent))]
    public virtual string Name { get; set; }
    ....}

And the following for validation:

public static class ExtendedValidation
{
    private static Dictionary<Type, bool> extendedValidationExemptions = new Dictionary<Type, bool>();


    /// <summary>
    /// Disable extended validation for a specific type
    /// </summary>
    /// <param name="type"></param>
    public static void DisableExtendedValidation(Type type)
    {
        extendedValidationExemptions[type] = true;
    }
    /// <summary>
    /// Clear any EV exemptions
    /// </summary>
    public static void Reset()
    {
        extendedValidationExemptions.Clear();
    }

    /// <summary>
    /// Check if a class should perform extended validation
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static bool IsExtendedValidationEnabled(Type type)
    {
        if (extendedValidationExemptions.ContainsKey(type))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}






[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]

public class ExtendedValidationRequiredAttribute : RequiredAttribute
{


    private Type _type;
    // Summary:
    //     Initializes a new instance of the System.ComponentModel.DataAnnotations.RequiredAttribute
    //     class.
    public ExtendedValidationRequiredAttribute(Type type)
    {
        _type = type;
    }



    // Summary:
    //     Checks that the value of the required data field is not empty.
    //
    // Parameters:
    //   value:
    //     The data field value to validate.
    //
    // Returns:
    //     true if validation is successful; otherwise, false.
    //
    // Exceptions:
    //   System.ComponentModel.DataAnnotations.ValidationException:
    //     The data field value was null.
    public override bool IsValid(object value)
    {
        if (ExtendedValidation.IsExtendedValidationEnabled(_type))
        {
            return base.IsValid(value);
        }
        else
        {
            return true;
        }


    }




}

Is there any way I can get around passing the type explicitly into the validator? I want to be able to enable/disable these validation attributes programmatically.

For example if I am editing a Child, but a Parent's [Required] fields would cause me to have problems, I would disable typeof(Parent) in the extendedValidator, and then Validation should work OK. I am just worried about performance impact with all the typeof() going on.

My problem that this attempts to address is when I am editing a class such as

public class Child {

[Required] public virtual int id {get;set;}

[Required] public virtual Parent parent {get;set;}

.... }

My form just has the Parent ID (that is all that is needed in my EF or hibernate app), but it will not validate unless the Parent passed in the form has all of the required fields -- which is rather wasteful.

Answers


You could override ValidationAttribute.IsValid Method (Object, ValidationContext)

protected virtual ValidationResult IsValid(
    Object value,
    ValidationContext validationContext
)

And access members of ValidationContext Class


Need Your Help

Adding 30 seconds to NSDate

ios cocoa-touch nsdate uilocalnotification date-arithmetic

How can I convert an NSDate to seconds? I need it in seconds so that I can added 30 secs to the date and then convert back to NSDate to schedule a local notification. Any better ways of doing that ...

How to convert image sequences (PNG) into Animation File (gif/mov/others) (iPhone)?

iphone objective-c graphics animation

I have a sequence of images (PNG format) in my iphone app. It is saved in the app's sandbox doc folder. How do I create animation file from these images?