2

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?

iuristona
  • 927
  • 13
  • 30
  • Could you clarify what do you mean by `some situations`? Did you mean different actions? – Darin Dimitrov Sep 22 '11 at 18:46
  • Example: A user can have an authorization to create a 14 years old person. To be clear, my question is not to solve the problem in question, but more about how to treat a MVC architecture problem. – iuristona Sep 22 '11 at 19:06

3 Answers3

1

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.

iuristona
  • 927
  • 13
  • 30
1

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.

Community
  • 1
  • 1
Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
0

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.

Community
  • 1
  • 1
counsellorben
  • 10,924
  • 3
  • 40
  • 38