简体   繁体   中英

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

I am using an 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, eg 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 eg 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.

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

protected virtual ValidationResult IsValid(
    Object value,
    ValidationContext validationContext
)

And access members of ValidationContext Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM