My task is to perform validation on form which fields are constructed dynamically(upon database query). I would like to use data annotations. While model is dynamic I can’t decorate properties with annotations, but I can use custom metadata provider for example inheriting from DataAnnotationsModelMetadataProvider.
Simply in global.asax at Application_start I supplied my own MetaDataProvider:
ModelMetadataProviders.Current = new MetadataProvider.CustomModelMetadataProvider();
I made a little hack, cause ModelMetadataProviders.Current is per application, my problem needed serving different metadata in each request, but it was not so hard.
This work fine for emulating IsRequired attribute, because metadata provider uses System.Web.Mvc.ModelMetadata and there is IsRequired property , but there is no property such as RegularExpression or anything similar.
So I run debugger and looked at ModelMetadata returned by original DataAnnotationsModelMetadataProvider for property with RegularExpression attribute, and I hadn’t found regular expression there anyway.
I would love to get some hints on that.
I figured answer (by inspecting MVC 3 source code) which is as follows:
ModelValidatorProviderfor example inheriting fromDataAnnotationsModelValidatorProviderGetValidatorsmethodModelValidatorProviders.Providers collectionGetValidatorsmethod returnsIEnumerable<ModelValidator>so its enough to returnRegularExpressionAttributeAdapterwhich inhertis fromModelValidator.