Search code examples
asp.net-mvc-3entity-framework-4.1data-annotationsvalidationattributecomponentmodel

How to programatically turn on/off a Data Annotation Validation Attribute


So, I am using ASP.NET MVC 3 and Entity Framework 4.1 (code-first).

I have a class like this:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    [Range(18, 99)]
    public int Age { get; set; }
}

The range validation is fired correctly. But, for example, in some situations I would like to change the range for the Age attribute. Or even turn it off. How could I do it without changing my Model class? Is this possible to made programatically?


Solution

  • I just realised the solution for this case.

    Eg. A user can have an authorization to create a 14 years old person.

    Before save the Model, we can invoke DataContext.GetValidationErrors() and infer if the only error validation is that we want to disable, and then set

    DataContext.Configuration.ValidateOnSaveEnabled = false;

    So, this way we are able to save the model.