StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

asp.net Mvc-3Ef Code-FirstEntity Framework-4.1

asp.net Mvc-3 Problem Overview


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?

asp.net Mvc-3 Solutions


Solution 1 - asp.net Mvc-3

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

> Specifies the maximum length of array > or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

> Specifies the minimum and maximum > length of characters that are allowed > in a data field.

Solution 2 - asp.net Mvc-3

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.

Solution 3 - asp.net Mvc-3

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; }
 }

Solution 4 - asp.net Mvc-3

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.

Solution 5 - asp.net Mvc-3

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.

Solution 6 - asp.net Mvc-3

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/

Solution 7 - asp.net Mvc-3

You can use :

[StringLength(8, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
public string Address { get; set; }

The error message created by the preceding code would be "Address length must be between 6 and 8.".

MSDN: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0

Solution 8 - asp.net Mvc-3

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.

Solution 9 - asp.net Mvc-3

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick GoloborodkoView Question on Stackoverflow
Solution 1 - asp.net Mvc-3SwaffView Answer on Stackoverflow
Solution 2 - asp.net Mvc-3MannIncognitoView Answer on Stackoverflow
Solution 3 - asp.net Mvc-3gmail userView Answer on Stackoverflow
Solution 4 - asp.net Mvc-3Abhishek DeoView Answer on Stackoverflow
Solution 5 - asp.net Mvc-3Nilesh MoradiyaView Answer on Stackoverflow
Solution 6 - asp.net Mvc-3Zonke-Bonke S'cekeleshe MsibiView Answer on Stackoverflow
Solution 7 - asp.net Mvc-3LukasCwajView Answer on Stackoverflow
Solution 8 - asp.net Mvc-3ZerotoinfinityView Answer on Stackoverflow
Solution 9 - asp.net Mvc-3KoenView Answer on Stackoverflow