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

2.6k Views Asked by At

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?

3

There are 3 best solutions below

0
iuristona On BEST ANSWER

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.

0
counsellorben On

Yes, it is possible to inject validators programmatically. Altering existing validators presents separate issues, as some attributes are read-only, so you may have to delete and replace your existing validator.

You can add a class to work on the validators by following my answer to this question.

0
Adam Tuliper On

You can use the IValidatableObject interface and define custom validation rules.

See my answer at:

Using Data Annotations to make a field required while searching for another in a form mvc 3

Its usually just a matter of implementing the interface and determine when to enforce your rules.