ASP.Net MVC3, DataAnnotations, and Dynamic Validation

I am creating an MVC 3 application that needs to set runtime data validation rules based on external data (e.g. Required, MinimumLength, MaximumLength). It is natural to use data annotations in MVC 3, however, property attributes that provide validation metadata are set at compile time.

Is there a template for using 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 know TypeDescriptor , but I don’t see the ability to change instance property attributes (only class level attributes for an instance or property level attributes for a type).

+4
source share
2 answers

It seems natural to use data annotations in MVC 3

Not for me. I never liked data annotations because of their declarative nature. And performing checks in declarative mode limits the possibilities. I have always loved and used FluentValidation.NET .

+4
source

Perhaps you can use the IDataErrorInfo interface (which MVC can use) to write your custom, dynamic validation rules.

+1
source

Source: https://habr.com/ru/post/1381834/


All Articles