Ahmed Khalaf
Ahmed Khalaf

Reputation: 1220

MVC Model Validation Programmatic Registration support

Today (15th Jan 2010) Scott blogged about the ASP.NET MVC2 model-validation

http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

Anyone knows how can someone add validation rules at runtime programmatically ?

"Programmatic Registration" is a similar functionality supported by ValidationAspects

// register lambda syntax validation functions
typeof(User).GetProperty("Name").AddValidation<string>((name, context) => 
  { if (!Exists(name)) { throw new ValidationException("Username is unknown"); } } );

// register validation factories (classes)
typeof(User).GetProperty("Name").AddValidation(new [] { new NotNullOrEmpty()} );

// don't like strings?
TypeOf<User>.Property(user => user.Name).AddValidation(new [] { new NotNullOrEmpty()} );

Upvotes: 3

Views: 828

Answers (2)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

Attributes are created at compile-time, not run-time. They cannot be changed after compile-time.

There are several run-time validation options, however. My favorite is Fluent Validation. You create validation classes that execute at run-time. You are more or less limited to only static data, and data from the model, however.

Upvotes: 0

John Farrell
John Farrell

Reputation: 24754

To provide custom metadata you'll have to implement the abstract class ModelMetadataProvider and register it inside your global.asax:

           ModelMetadataProviders.Current = new ConventionMetadataProvider();

This isn't adding validation attributes at runtime. Your simply providing ALL the validation information into the ModelMetadata classes which are then read by the HTML.EditorFor bits.

Upvotes: 1

Related Questions