[asp.net-mvc-3] StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

What is the difference in behavior of [MaxLength] and [StringLength] attributes?

As far as I can tell (with the exception that [MaxLength] can validate the maximum length of an array) these are identical and somewhat redundant?

This question is related to asp.net-mvc-3 ef-code-first entity-framework-4.1

The answer is


Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):

The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:

[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }

Will output the following if it is over the character limit: "Address can have a max of 100 characters"

The placeholders I am aware of are:

  • {0} = Property Name
  • {1} = Max Length
  • {2} = Min Length

Much thanks to bloudraak for initially pointing this out.


One another point to note down is in MaxLength attribute you can only provide max required range not a min required range. While in StringLength you can provide both.


All good answers...From the validation perspective, I also noticed that MaxLength gets validated at the server side only, while StringLength gets validated at client side too.


I have resolved it by adding below line in my context:

modelBuilder.Entity<YourObject>().Property(e => e.YourColumn).HasMaxLength(4000);

Somehow, [MaxLength] didn't work for me.


When using the attribute to restrict the maximum input length for text from a form on a webpage, the StringLength seems to generate the maxlength html attribute (at least in my test with MVC 5). The one to choose then depnds on how you want to alert the user that this is the maximum text length. With the stringlength attribute, the user will simply not be able to type beyond the allowed length. The maxlength attribute doesn't add this html attribute, instead it generates data validation attributes, meaning the user can type beyond the indicated length and that preventing longer input depends on the validation in javascript when he moves to the next field or clicks submit (or if javascript is disabled, server side validation). In this case the user can be notified of the restriction by an error message.


Following are the results when we use both [MaxLength] and [StringLength] attributes, in EF code first. If both are used, [MaxLength] wins the race. See the test result in studentname column in below class

 public class Student
 {
    public Student () {}

    [Key]
    [Column(Order=1)]
    public int StudentKey { get; set; }

    //[MaxLength(50),StringLength(60)]    //studentname column will be nvarchar(50)
    //[StringLength(60)]    //studentname column will be nvarchar(60)
    [MaxLength(50)] //studentname column will be nvarchar(50)
    public string StudentName { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }
 }

MaxLengthAttribute means Max. length of array or string data allowed

StringLengthAttribute means Min. and max. length of characters that are allowed in a data field

Visit http://joeylicc.wordpress.com/2013/06/20/asp-net-mvc-model-validation-using-data-annotations/


Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to ef-code-first

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType There is already an object named in the database The entity type <type> is not part of the model for the current context Entity Framework 6 Code first Default value Unique Key constraints for multiple columns in Entity Framework Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why? How to delete and recreate from scratch an existing EF Code First database Entity Framework: One Database, Multiple DbContexts. Is this a bad idea? Ignoring a class property in Entity Framework 4.1 Code First

Examples related to entity-framework-4.1

Entity Framework Join 3 Tables How to include a child object's child object in Entity Framework 5 Ignoring a class property in Entity Framework 4.1 Code First The type or namespace name 'Entity' does not exist in the namespace 'System.Data' Validation failed for one or more entities. See 'EntityValidationErrors' property for more details StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First Entity framework code-first null foreign key How do I detach objects in Entity Framework Code First? Entity Framework Code First - two Foreign Keys from same table How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?