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?
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?
MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.
From MSDN:
StringLength is a data annotation that will be used for validation of user input.
From MSDN:
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:
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:
Much thanks to bloudraak for initially pointing this out.
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/
Following are the results when we use both
[MaxLength]
and[StringLength]
attributes, inEF code first
. If both are used,[MaxLength]
wins the race. See the test result instudentname
column in below classOne 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.