views:

189

answers:

1

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()} );
+1  A: 

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.

jfar
You mean we can't add validation attributes at runtime with default functionality?Can you elaborate please :)
Ahmed Khalaf