4

I'm creating an MVC 3 application that needs to establish data validation rules at runtime based on external data (e.g. Required, MinimumLength, MaximumLength). It seems natural to use Data Annotations in MVC 3, however the property attributes that provide validation metadata are set at compile-time.

Is there a pattern to use Data Annotations with metadata provided at runtime?

Example:

public string Text { get; set; }

public void SetIsRequired(string propertyName, bool required)
{
    // Somehow find the property 'propertyName' and create/remove a RequiredAttribute
    // on that property
}

...
SetIsRequired("Text", true);

I'm aware of TypeDescriptor, but don't see an option to modify attributes of a property of an instance (only class level attributes on an instance, or property level attributes for a type).

2 Answers 2

4

It seems natural to use Data Annotations in MVC 3

Not for me. I never really liked data annotations due to their declarative nature. And doing validation in a declarative way limits capabilities. I have always liked and use FluentValidation.NET.

Sign up to request clarification or add additional context in comments.

3 Comments

Interesting alternative. Does FluentValidation.NET work well with Entity Framework Code First?
@EricJ., yes it does work with any model. Simply install the FluentValidation.MVC3 NuGet, register the fluent validation model validator provider in your Application_Start: FluentValidationModelValidatorProvider.Configure(); and then you could define validators for your models.
Cool! Does FluentValidation.Net generate the attributes to provide the same client side validation provided by DataAnnotations?
1

You could probably use the IDataErrorInfo interface (which MVC can consume) to write your custom, dynamic, validation rules.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.