{"id":3240,"date":"2014-03-20T21:05:58","date_gmt":"2014-03-20T21:05:58","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/03\/20\/dataannotations-dynamically-attaching-attributes-collection-of-common-programming-errors-2\/"},"modified":"2014-03-20T21:05:58","modified_gmt":"2014-03-20T21:05:58","slug":"dataannotations-dynamically-attaching-attributes-collection-of-common-programming-errors-2","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/03\/20\/dataannotations-dynamically-attaching-attributes-collection-of-common-programming-errors-2\/","title":{"rendered":"DataAnnotations dynamically attaching attributes-Collection of common programming errors"},"content":{"rendered":"<p>MVC has a hook to provide your own ModelValidatorProvider. By default MVC 2 uses a sub class of ModelValidatorProvider called DataAnnotationsModelValidatorProvider that is able to use System.DataAnnotations.ComponentModel.ValidationAttribute attributes for validation.<\/p>\n<p>The DataAnnotationsModelValidatorProvider uses reflection to find all the ValidationAttributes and simply loops through the collection to validate your models. All you need to do is override a method called GetValidators and inject your own attributes from whichever source you choose. I use this technique to do convention validations, the properties with DataType.Email attribute always gets passed through a regex, and use this technique to pull information from the database to apply more restrictive validations for &#8220;non-power&#8221; users.<\/p>\n<p>The following example simply says &#8220;always make any FirstName properties required&#8221;:<\/p>\n<pre><code> public class CustomMetadataValidationProvider : DataAnnotationsModelValidatorProvider\n {\n    protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes)\n    {\n        \/\/go to db if you want\n        \/\/var repository = ((MyBaseController) context.Controller).RepositorySomething;\n\n        \/\/find user if you need it\n        var user = context.HttpContext.User;\n\n        if (!string.IsNullOrWhiteSpace(metadata.PropertyName) &amp;&amp; metadata.PropertyName == \"FirstName\")\n            attributes = new List() {new RequiredAttribute()};\n\n        return base.GetValidators(metadata, context, attributes);\n    }\n}\n<\/code><\/pre>\n<p>All you have to do is register the provider in your Global.asax.cs file:<\/p>\n<pre><code>    protected void Application_Start()\n    {\n        ModelValidatorProviders.Providers.Add(new CustomMetadataValidationProvider());\n\n        AreaRegistration.RegisterAllAreas();\n\n        RegisterRoutes(RouteTable.Routes);\n    }\n<\/code><\/pre>\n<p>The end result:<\/p>\n<p><img decoding=\"async\" src=\"http:\/\/i.stack.imgur.com\/KKYhF.png\" \/><\/p>\n<p>with this model:<\/p>\n<pre><code>public class Person\n{\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n    public DateTime Birthday { get; set; }\n}\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>MVC has a hook to provide your own ModelValidatorProvider. By default MVC 2 uses a sub class of ModelValidatorProvider called DataAnnotationsModelValidatorProvider that is able to use System.DataAnnotations.ComponentModel.ValidationAttribute attributes for validation. The DataAnnotationsModelValidatorProvider uses reflection to find all the ValidationAttributes and simply loops through the collection to validate your models. All you need to do is [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-3240","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/3240","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=3240"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/3240\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=3240"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=3240"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=3240"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}