Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8710519
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T04:38:45+00:00 2026-06-13T04:38:45+00:00

I have a requirement to add StringLengthAttribute validation to a lot of models in

  • 0

I have a requirement to add StringLengthAttribute validation to a lot of models in the existing ASP.NET MVC 4 project and am trying to do this automatically through my own model metadata provider derived from DataAnnotationsModelMetadataProvider.

It works perfectly with RequiredAttribute and some other data annotation attributes (I get both client-side and server-side validation working), however validation for the string length is not added – find the minimal example below.

public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes,
                                                    Type containerType,
                                                    Func<object> modelAccessor,
                                                    Type modelType,
                                                    string propertyName)
    {
        StringLengthAttribute lengthAttribute = new StringLengthAttribute(256);
        attributes = attributes.Union(new[] { lengthAttribute });
        return base.CreateMetadata(attributes,
                                   containerType,
                                   modelAccessor,
                                   modelType,
                                   propertyName);
    }
}

So, looks like StringLengthAttribute it being handled in some special way. Any ideas on how to make it work or a better implementation idea?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T04:38:46+00:00Added an answer on June 13, 2026 at 4:38 am

    After playing around, I couldn’t get the StringLength attribute to fire either.

    Not ideal, but i guess an alternative solution is to the use a global ModelValidatorProvider class. Granted you won’t get the built in Javascript that is provided by the StringLengthAttribute and you’d be writing your own logic, but its a possible quick fix for a problem you can solve later?

        public class MyCustomModelValidatorProvider : ModelValidatorProvider
    {
        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
        {
            return new List<ModelValidator>() { new MyCustomModelValidator(metadata, context) };
        }
    
        public class MyCustomModelValidator : ModelValidator
        {
            public MyCustomModelValidator(ModelMetadata metadata, ControllerContext context)
                : base(metadata, context)
            {   }
    
            public override IEnumerable<ModelValidationResult> Validate(object container)
            {
                var model = this.Metadata.Model; 
                if (model is string)
                {
                    var value = model as string;
    
                    if (String.IsNullOrEmpty(value) || value.Length > 256)
                    {
                        var validationResult = new ModelValidationResult();
                        validationResult.Message = (this.Metadata.DisplayName ?? this.Metadata.PropertyName) 
                            + " needs to be no more then 256 characters";
    
                        return new List<ModelValidationResult>() { validationResult };
                    }
                }
    
                return new List<ModelValidationResult>();
            }
        }
    
    }
    

    Add MyCustomModelValidator to the collection in Global.asax

            protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
    
            // Use LocalDB for Entity Framework by default
            Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
    
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
    
    
            ModelValidatorProviders.Providers.Add(new MyCustomModelValidatorProvider());
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am working on this site: http://www.problemio.com and I have a requirement to add
I have a requirement to add a standard drop-down from which you can select
Can i add two header text in Datagrid? My Requirement is to have two
I have requirement to disable copy/paste/cut operations on a textbox. For this purpose I
I have a requirement to add commenting system to a page (similar to 'Post
I'm working in Drupal 6. I have a requirement to add a particular block
I have a requirement to create an installer for an Outlook 2003 add-in that
We have a requirement to add an event reminder when a user enters their
I have a requirement to add an alternative language version of a single article
In my native iPhone Application, I have a requirement to add a reminder to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.