Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top