177

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?

Mike G
  • 4,232
  • 9
  • 40
  • 66
Nick Goloborodko
  • 2,883
  • 3
  • 21
  • 38
  • 1
    I'm not sure about ASP.NET MVC but for EF there should be no difference: http://stackoverflow.com/questions/5414611/entity-framework-validation-confusion-maximum-string-length-of-128/5416428#5416428 – Ladislav Mrnka Apr 19 '11 at 13:50
  • 1
    The stringLength doesnt affect the migrations col size when you change it. – Cas Bloem May 12 '16 at 15:04
  • 1
    @CasBloem StringLength does in fact get picked up by EntityFramework and will impact column lengths -- at least in version 6. – jakejgordon Mar 26 '18 at 01:42

9 Answers9

241

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.

Swaff
  • 13,548
  • 4
  • 26
  • 26
  • 10
    Also note that by default MVC 3 does not recognized `MaxLengthAttribute`, while EF does recognize `StringLengthAttribute` – marcind Apr 19 '11 at 18:09
  • 21
    So really there is no need for MaxLength since you can use StringLength in EF and it also infers the string field size. Why then did they even create MaxLength? – Matt Johnson-Pint Dec 01 '11 at 00:45
  • 4
    @MattJohnson - I seem to recall that the decision to create a new MaxLength attribute was for semantics because StringLength implies string data but MaxLength can apply to binary data as well. But it sure as hell is inconvenient. – Josh Jun 07 '12 at 12:23
  • @MattJohnson - I've never used code first but [the comment on this answer](http://stackoverflow.com/a/5678340/73226) implies that there is some difference. – Martin Smith Aug 20 '13 at 21:50
  • 1
    @MartinSmith - I just tried using StringLength and it worked for me and I'm using EF6 RC1 so I don't think the comments there are correct – Colin Sep 18 '13 at 12:37
  • Is there some kind of a list that specifies which attributes are used by EF and which by ASP.NET validation? The both use the same namespace of ```System.ComponentModel.DataAnnotations```, but only seem to use a subset of attributes defined in there. – gligoran Nov 07 '15 at 16:23
  • Can we use both MaxLength and StringLength at the same time? Or will there be a conflict? – Dima Jul 26 '16 at 11:38
  • 8
    Why does `[MaxLength]` have an ErrorMessage then? – Zapnologica Aug 12 '16 at 09:20
  • Why would you ever want to set these to different values? – Jonathan Wood May 21 '20 at 17:16
  • If you are looking for a way to state that you _intended_ nvarchar(max) - i.e. that it wasn't an oversight and you didn't forget to set a char limit - the MaxLength attribute has a 0-arg ctor that has this effect - i.e. `[MaxLength]`. StringLength does not. This is of course personal preference. – pbristow Jul 27 '22 at 00:00
60

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.

Community
  • 1
  • 1
MannIncognito
  • 792
  • 5
  • 8
16

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; }
 }
gmail user
  • 2,753
  • 4
  • 33
  • 42
13

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.

Abhishek Deo
  • 139
  • 1
  • 3
5

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.

Nilesh Moradiya
  • 691
  • 1
  • 10
  • 19
  • 6
    Yes, but this is presumably why there's also a MinLength attribute: http://msdn.microsoft.com/EN-US/library/gg696756(v=VS.110,d=hv.2).aspx – Ian Griffiths Jul 24 '14 at 06:30
5

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/

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://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0

LukasCwaj
  • 71
  • 2
1

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.

Zerotoinfinity
  • 6,290
  • 32
  • 130
  • 206
0

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.

Koen
  • 49
  • 6